debounce.es6.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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 () {
  32. const context = this;
  33. const args = arguments;
  34. const later = function () {
  35. timeout = null;
  36. if (!immediate) {
  37. result = func.apply(context, args);
  38. }
  39. };
  40. const callNow = immediate && !timeout;
  41. clearTimeout(timeout);
  42. timeout = setTimeout(later, wait);
  43. if (callNow) {
  44. result = func.apply(context, args);
  45. }
  46. return result;
  47. };
  48. };