Upgraded drupal core with security updates
[yaffs-website] / web / core / misc / debounce.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
31   'use strict';
32
33   var timeout;
34   var result;
35   return function () {
36     var context = this;
37     var args = arguments;
38     var later = function () {
39       timeout = null;
40       if (!immediate) {
41         result = func.apply(context, args);
42       }
43     };
44     var callNow = immediate && !timeout;
45     clearTimeout(timeout);
46     timeout = setTimeout(later, wait);
47     if (callNow) {
48       result = func.apply(context, args);
49     }
50     return result;
51   };
52 };