problems(js): add “2676. Throttle”
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
c5298dbc0a
commit
85a6ee72b0
1 changed files with 35 additions and 0 deletions
35
problems/throttle.js
Normal file
35
problems/throttle.js
Normal file
|
@ -0,0 +1,35 @@
|
|||
/**
|
||||
* @param {Function} fn
|
||||
* @param {number} t
|
||||
* @return {Function}
|
||||
*/
|
||||
var throttle = function(fn, t) {
|
||||
let on_cooldown = false;
|
||||
let queuedArgs = null;
|
||||
|
||||
const handler = () => {
|
||||
if (queuedArgs === null) {
|
||||
on_cooldown = false;
|
||||
return;
|
||||
}
|
||||
|
||||
fn.apply(null, queuedArgs);
|
||||
queuedArgs = null;
|
||||
on_cooldown = true;
|
||||
|
||||
setTimeout(handler, t);
|
||||
};
|
||||
|
||||
return function(...args) {
|
||||
queuedArgs = args;
|
||||
if (!on_cooldown) {
|
||||
handler();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* const throttled = throttle(console.log, 100);
|
||||
* throttled("log"); // logged immediately.
|
||||
* throttled("log"); // logged at t=100ms.
|
||||
*/
|
Loading…
Reference in a new issue