Last active
December 27, 2020 00:29
-
-
Save ikbelkirasan/67e5939eab550f926d2316c92cf5d5d9 to your computer and use it in GitHub Desktop.
Debounce a function (Typescript)
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
type Fn = (...args: any[]) => any; | |
type Callback<F extends Fn> = F extends Fn | |
? (...args: Parameters<F>) => ReturnType<F> | |
: never; | |
function debounce<T extends Fn, O extends Callback<T>>( | |
func: O, | |
wait: number, | |
immediate?: boolean | |
): O { | |
let timeout: NodeJS.Timeout, result: ReturnType<O>; | |
return function (...args) { | |
clearTimeout(timeout); | |
timeout = setTimeout(() => { | |
timeout = null; | |
if (!immediate) { | |
result = func.call(this, ...args); | |
} | |
}, wait); | |
if (immediate && !timeout) { | |
result = func.call(this, ...args); | |
} | |
return result; | |
} as O; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment