debounce.js 698 B

123456789101112131415161718192021222324252627282930
  1. /**
  2. * Debounce a function to delay invoking until wait (ms) have elapsed since the last invocation.
  3. * @param {function(...*): *} fn The function to be debounced.
  4. * @param {number} wait Milliseconds to wait before invoking again.
  5. * @return {function(...*): void} The debounced function.
  6. */
  7. function debounce(fn, wait) {
  8. /**
  9. * A cached setTimeout handler.
  10. * @type {number | undefined}
  11. */
  12. let timer;
  13. /**
  14. * @returns {void}
  15. */
  16. function debounced() {
  17. const context = this;
  18. const args = arguments;
  19. clearTimeout(timer);
  20. timer = setTimeout(function () {
  21. return fn.apply(context, args);
  22. }, wait);
  23. }
  24. return debounced;
  25. }
  26. module.exports = debounce;