Security update to Drupal 8.4.6
[yaffs-website] / web / core / misc / debounce.es6.js
1 /**
2  * @file
3  * Adapted from underscore.js with the addition Drupal namespace.
4  */
5
6 /**
7  * Limits the invocations of a function in a given time frame.
8  *
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.
11  *
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
15  * conditions.
16  *
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.
25  *
26  * @return {function}
27  *   The debounced function.
28  */
29 Drupal.debounce = function (func, wait, immediate) {
30   let timeout;
31   let result;
32   return function () {
33     const context = this;
34     const args = arguments;
35     const later = function () {
36       timeout = null;
37       if (!immediate) {
38         result = func.apply(context, args);
39       }
40     };
41     const 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 };