2676. Throttle
https://leetcode.com/problems/throttle/
Javascript
var throttle = function(fn, t) {
let lastArgs = null
let isBlocked = false
const executor = () => {
if (lastArgs === null) {
isBlocked = false
return
}
fn(...lastArgs)
lastArgs = null
setTimeout(executor, t)
}
return function(...args) {
if (isBlocked) {
lastArgs = args
return
}
fn(...args)
isBlocked = true
setTimeout(executor, t)
}
};
/**
* const throttled = throttle(console.log, 100);
* throttled("log"); // logged immediately.
* throttled("log"); // logged at t=100ms.
*/
Typescript
type F = (...args: any[]) => void
function throttle(fn: F, t: number): F {
let lastArgs: any | null = null
let isBlocked: Boolean = false
const executor = () => {
if (lastArgs === null) {
isBlocked = false
return
}
fn(...lastArgs)
lastArgs = null
setTimeout(executor, t)
}
return function (...args) {
if (isBlocked) {
lastArgs = args
return
}
fn(...args)
isBlocked = true
setTimeout(executor, t)
}
};