Last active
March 17, 2020 13:40
-
-
Save bwlt/a51faa879223f0a41807b2e63b7130c0 to your computer and use it in GitHub Desktop.
A debounce function with type safety
This file contains 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 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