Skip to content

Instantly share code, notes, and snippets.

@ikbelkirasan
Last active December 27, 2020 00:29
Show Gist options
  • Save ikbelkirasan/67e5939eab550f926d2316c92cf5d5d9 to your computer and use it in GitHub Desktop.
Save ikbelkirasan/67e5939eab550f926d2316c92cf5d5d9 to your computer and use it in GitHub Desktop.
Debounce a function (Typescript)
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