debounce.js 458 B

12345678910111213141516171819
  1. "use strict";
  2. let timeout = null;
  3. function debounce(func, wait = 500, immediate = false) {
  4. if (timeout !== null)
  5. clearTimeout(timeout);
  6. if (immediate) {
  7. const callNow = !timeout;
  8. timeout = setTimeout(() => {
  9. timeout = null;
  10. }, wait);
  11. if (callNow)
  12. typeof func === "function" && func();
  13. } else {
  14. timeout = setTimeout(() => {
  15. typeof func === "function" && func();
  16. }, wait);
  17. }
  18. }
  19. exports.debounce = debounce;