Skip to content

Instantly share code, notes, and snippets.

@sekoyo
Last active August 26, 2023 00:20
Show Gist options
  • Save sekoyo/b45c4337335bbf191a0335e5fb4ecfbc to your computer and use it in GitHub Desktop.
Save sekoyo/b45c4337335bbf191a0335e5fb4ecfbc to your computer and use it in GitHub Desktop.
throttle.ts
export const throttle = <FN extends (...args: Parameters<FN>) => ReturnType<FN>>(
fn: FN,
delay: number
) => {
let wait = false
let timeout: undefined | number
let prevValue: ReturnType<FN> | undefined = undefined
const throttleFn = (...args: Parameters<FN>) => {
if (wait) {
// prevValue always defined by the
// time wait is true
return prevValue!
}
const val = fn(...args)
prevValue = val
wait = true
timeout = window.setTimeout(() => {
wait = false
}, delay)
return val
}
throttleFn.cancel = () => {
clearTimeout(timeout)
}
return throttleFn
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment