throttle.js 861 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. /**
  2. * Throttle decorator
  3. * @param {Function} fn
  4. * @param {Number} freq
  5. * @return {Function}
  6. */
  7. function throttle(fn, freq) {
  8. let timestamp = 0;
  9. let threshold = 1000 / freq;
  10. let lastArgs;
  11. let timer;
  12. const invoke = (args, now = Date.now()) => {
  13. timestamp = now;
  14. lastArgs = null;
  15. if (timer) {
  16. clearTimeout(timer);
  17. timer = null;
  18. }
  19. fn.apply(null, args);
  20. }
  21. const throttled = (...args) => {
  22. const now = Date.now();
  23. const passed = now - timestamp;
  24. if ( passed >= threshold) {
  25. invoke(args, now);
  26. } else {
  27. lastArgs = args;
  28. if (!timer) {
  29. timer = setTimeout(() => {
  30. timer = null;
  31. invoke(lastArgs)
  32. }, threshold - passed);
  33. }
  34. }
  35. }
  36. const flush = () => lastArgs && invoke(lastArgs);
  37. return [throttled, flush];
  38. }
  39. export default throttle;