throttle.js 702 B

123456789101112131415161718192021222324252627282930313233
  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(force, args) {
  13. const now = Date.now();
  14. if (force || now - timestamp > threshold) {
  15. if (timer) {
  16. clearTimeout(timer);
  17. timer = null;
  18. }
  19. timestamp = now;
  20. return fn.apply(null, args);
  21. }
  22. if (!timer) {
  23. timer = setTimeout(() => {
  24. timer = null;
  25. timestamp = Date.now();
  26. return fn.apply(null, args);
  27. }, threshold - (now - timestamp));
  28. }
  29. };
  30. }
  31. export default throttle;