throttle.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. var now = require('./now.js');
  2. // Returns a function, that, when invoked, will only be triggered at most once
  3. // during a given window of time. Normally, the throttled function will run
  4. // as much as it can, without ever going more than once per `wait` duration;
  5. // but if you'd like to disable the execution on the leading edge, pass
  6. // `{leading: false}`. To disable execution on the trailing edge, ditto.
  7. function throttle(func, wait, options) {
  8. var timeout, context, args, result;
  9. var previous = 0;
  10. if (!options) options = {};
  11. var later = function() {
  12. previous = options.leading === false ? 0 : now();
  13. timeout = null;
  14. result = func.apply(context, args);
  15. if (!timeout) context = args = null;
  16. };
  17. var throttled = function() {
  18. var _now = now();
  19. if (!previous && options.leading === false) previous = _now;
  20. var remaining = wait - (_now - previous);
  21. context = this;
  22. args = arguments;
  23. if (remaining <= 0 || remaining > wait) {
  24. if (timeout) {
  25. clearTimeout(timeout);
  26. timeout = null;
  27. }
  28. previous = _now;
  29. result = func.apply(context, args);
  30. if (!timeout) context = args = null;
  31. } else if (!timeout && options.trailing !== false) {
  32. timeout = setTimeout(later, remaining);
  33. }
  34. return result;
  35. };
  36. throttled.cancel = function() {
  37. clearTimeout(timeout);
  38. previous = 0;
  39. timeout = context = args = null;
  40. };
  41. return throttled;
  42. }
  43. module.exports = throttle;