throttle
See debounce if you want your function to run at the end of the N seconds.
typescriptjavascript
const throttle = <T extends CallableFunction>(fn: T, delay: number): T => {
let canRun = true
return ((...args: any[]) => {
if (canRun) {
fn(...args)
canRun = false
setTimeout(() => {
canRun = true
}, delay)
}
}) as any
}
const throttle = (fn, delay) => {
let canRun = true
return (...args) => {
if (canRun) {
fn(...args)
canRun = false
setTimeout(() => {
canRun = true
}, delay)
}
}
}