debounce.es6.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /**
  2. * @file
  3. * Adapted from underscore.js with the addition Drupal namespace.
  4. */
  5. /**
  6. * Limits the invocations of a function in a given time frame.
  7. *
  8. * The debounce function wrapper should be used sparingly. One clear use case
  9. * is limiting the invocation of a callback attached to the window resize event.
  10. *
  11. * Before using the debounce function wrapper, consider first whether the
  12. * callback could be attached to an event that fires less frequently or if the
  13. * function can be written in such a way that it is only invoked under specific
  14. * conditions.
  15. *
  16. * @param {function} func
  17. * The function to be invoked.
  18. * @param {number} wait
  19. * The time period within which the callback function should only be
  20. * invoked once. For example if the wait period is 250ms, then the callback
  21. * will only be called at most 4 times per second.
  22. * @param {bool} immediate
  23. * Whether we wait at the beginning or end to execute the function.
  24. *
  25. * @return {function}
  26. * The debounced function.
  27. */
  28. Drupal.debounce = function(func, wait, immediate) {
  29. let timeout;
  30. let result;
  31. return function(...args) {
  32. const context = this;
  33. const later = function() {
  34. timeout = null;
  35. if (!immediate) {
  36. result = func.apply(context, args);
  37. }
  38. };
  39. const callNow = immediate && !timeout;
  40. clearTimeout(timeout);
  41. timeout = setTimeout(later, wait);
  42. if (callNow) {
  43. result = func.apply(context, args);
  44. }
  45. return result;
  46. };
  47. };