throttle.js 735 B

1234567891011121314151617181920212223242526272829303132333435
  1. 'use strict';
  2. /**
  3. * Throttle decorator
  4. * @param {Function} fn
  5. * @param {Number} freq
  6. * @return {Function}
  7. */
  8. function throttle(fn, freq) {
  9. let timestamp = 0;
  10. const threshold = 1000 / freq;
  11. let timer = null;
  12. return function throttled() {
  13. const force = this === true;
  14. const now = Date.now();
  15. if (force || now - timestamp > threshold) {
  16. if (timer) {
  17. clearTimeout(timer);
  18. timer = null;
  19. }
  20. timestamp = now;
  21. return fn.apply(null, arguments);
  22. }
  23. if (!timer) {
  24. timer = setTimeout(() => {
  25. timer = null;
  26. timestamp = Date.now();
  27. return fn.apply(null, arguments);
  28. }, threshold - (now - timestamp));
  29. }
  30. };
  31. }
  32. export default throttle;