-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2676. Throttle.js
60 lines (54 loc) · 1.44 KB
/
2676. 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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/**
* @param {Function} fn
* @param {number} t
* @return {Function}
*/
// Approach 1: Recursive setTimeout Calls
var throttle = function(fn, t) {
let timeoutInProgress = null;
let argsToProcess = null;
const timeoutFunction = () => {
if (argsToProcess === null) {
timeoutInProgress = null; // enter the waiting phase
} else {
fn(...argsToProcess);
argsToProcess = null;
timeoutInProgress = setTimeout(timeoutFunction, t);
}
};
return function throttled(...args) {
if (timeoutInProgress) {
argsToProcess = args;
} else {
fn(...args); // enter the looping phase
timeoutInProgress = setTimeout(timeoutFunction, t);
}
}
};
// Approach 2: setInterval + clearInterval
var throttle1 = function(fn, t) {
let intervalInProgress = null;
let argsToProcess = null;
const intervalFunction = () => {
if (argsToProcess === null) {
clearInterval(intervalInProgress);
intervalInProgress = null; // enter the waiting phase
} else {
fn(...argsToProcess);
argsToProcess = null;
}
};
return function throttled(...args) {
if (intervalInProgress) {
argsToProcess = args;
} else {
fn(...args); // enter the looping phase
intervalInProgress = setInterval(intervalFunction, t);
}
}
};
/**
* const throttled = throttle(console.log, 100);
* throttled("log"); // logged immediately.
* throttled("log"); // logged at t=100ms.
*/