throttle.js 824 B

123456789101112131415161718192021222324252627282930313233
  1. var now = require('../time/now');
  2. /**
  3. */
  4. function throttle(fn, delay){
  5. var context, timeout, result, args,
  6. diff, prevCall = 0;
  7. function delayed(){
  8. prevCall = now();
  9. timeout = null;
  10. result = fn.apply(context, args);
  11. }
  12. function throttled(){
  13. context = this;
  14. args = arguments;
  15. diff = delay - (now() - prevCall);
  16. if (diff <= 0) {
  17. clearTimeout(timeout);
  18. delayed();
  19. } else if (! timeout) {
  20. timeout = setTimeout(delayed, diff);
  21. }
  22. return result;
  23. }
  24. throttled.cancel = function(){
  25. clearTimeout(timeout);
  26. };
  27. return throttled;
  28. }
  29. module.exports = throttle;