Last active
August 26, 2023 00:20
-
-
Save dominictobias/b45c4337335bbf191a0335e5fb4ecfbc to your computer and use it in GitHub Desktop.
throttle.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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