-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy paththrottle.js
34 lines (32 loc) · 1022 Bytes
/
throttle.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* Returns a wrapper, passing the call to 'method' at maximum once per 'delay' milliseconds.
* Those calls that fall into the "cooldown" period, are ignored
*
* @param {Function} cb callback
* @param {number} delay - milliseconds
* @returns {Function} throttled callback
*/
export const throttle = (cb, delay) => {
let wait = false;
let savedArgs;
const wrapper = (...args) => {
if (wait) {
savedArgs = args;
return;
}
cb(...args);
wait = true;
setTimeout(() => {
wait = false;
if (savedArgs) {
// it's necessary to use spread operator
// otherwise if there will be more than one argument
// then only one argument will be passed
// https://github.com/AdguardTeam/Scriptlets/issues/284#issuecomment-1419464354
wrapper(...savedArgs);
savedArgs = null;
}
}, delay);
};
return wrapper;
};