Mercurial > hg > cmmr2012-drupal-site
comparison core/misc/debounce.es6.js @ 0:c75dbcec494b
Initial commit from drush-created site
author | Chris Cannam |
---|---|
date | Thu, 05 Jul 2018 14:24:15 +0000 |
parents | |
children | a9cd425dd02b |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:c75dbcec494b |
---|---|
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 (...args) { | |
33 const context = this; | |
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 }; |