Skip to content

Instantly share code, notes, and snippets.

@bwlt
Last active March 17, 2020 13:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bwlt/a51faa879223f0a41807b2e63b7130c0 to your computer and use it in GitHub Desktop.
Save bwlt/a51faa879223f0a41807b2e63b7130c0 to your computer and use it in GitHub Desktop.
A debounce function with type safety
export const MissingReturnValue = Symbol('MissingReturnValue')
export function debounce<Fn extends (...args: any[]) => any>(
fn: Fn,
ms: number
): (...args: Parameters<Fn>) => ReturnType<Fn> | typeof MissingReturnValue {
let debouncing = false
let lastReturnedValue:
| typeof MissingReturnValue
| ReturnType<Fn> = MissingReturnValue
let timeoutID: number
return function debounced(
...args: Parameters<Fn>
): ReturnType<Fn> | typeof MissingReturnValue {
if (debouncing === false) {
debouncing = true
} else {
clearTimeout(timeoutID)
}
timeoutID = setTimeout(() => {
debouncing = false
lastReturnedValue = fn.apply(fn, args)
}, ms)
return lastReturnedValue
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment