Skip to content

Instantly share code, notes, and snippets.

@steveruizok
Created March 27, 2021 15:24
Show Gist options
  • Save steveruizok/dee5dd449a456896829ff8ff4d3ebb94 to your computer and use it in GitHub Desktop.
Save steveruizok/dee5dd449a456896829ff8ff4d3ebb94 to your computer and use it in GitHub Desktop.
A typed throttle for Typescript.
export function throttle<T extends (...args: any[]) => any>(
fn: T,
wait: number
) {
let inThrottle: boolean, lastFn: any, lastTime: number
return function(...a: Parameters<T>): ReturnType<T> {
const context = this,
args = arguments
if (!inThrottle) {
lastTime = Date.now()
inThrottle = true
return fn.apply(context, args)
} else {
clearTimeout(lastFn)
lastFn = setTimeout(function() {
if (Date.now() - lastTime >= wait) {
lastTime = Date.now()
return fn.apply(context, args)
}
}, Math.max(wait - (Date.now() - lastTime), 0))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment