-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy paththrottle.js
41 lines (37 loc) · 864 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
35
36
37
38
39
40
41
let wait = false;
function throttle(message) {
if (wait) {
return;
}
wait = true;
setTimeout(() => {
console.log(message);
wait = false;
}, 100);
}
throttle("Hello"); // exec
throttle("World"); // cancelled
throttle("Hey"); // cancelled
// LeetCode - https://leetcode.com/problems/throttle/
// const throttlee = (fn, t) => {
// let pending = false;
// let nextArgs;
// const wrapper = (...args) => {
// nextArgs = args;
// if (!pending) {
// fn(...args);
// pending = true;
// nextArgs = undefined;
// setTimeout(() => {
// pending = false;
// if (nextArgs) wrapper(...nextArgs);
// }, t);
// }
// };
// return wrapper;
// };
/**
* const throttled = throttle(console.log, 100);
* throttled("log"); // logged immediately.
* throttled("log"); // logged at t=100ms.
*/