mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-09 15:59:06 +01:00
36 lines
641 B
JavaScript
36 lines
641 B
JavaScript
|
/**
|
||
|
* @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.
|
||
|
*/
|