debounce.js 1.5 KB

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