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