Skip to content

Instantly share code, notes, and snippets.

@joshuaaron
Created December 1, 2020 05:08
Show Gist options
  • Save joshuaaron/24f512bf4ccd9f00b6b38de95960646f to your computer and use it in GitHub Desktop.
Save joshuaaron/24f512bf4ccd9f00b6b38de95960646f to your computer and use it in GitHub Desktop.
Typescript versions of regular Debounce, and DebouncedPromised
const debounce = <F extends (...args: any[]) => any>(fn: F, delay: number) => {
let timeout: NodeJS.Timeout;
const debounced = (...args: any[]) => {
clearTimeout(timeout);
timeout = setTimeout(() => fn(...args), delay);
};
return debounced as (...args: Parameters<F>) => ReturnType<F>;
};
const debouncePromise = <F extends (...args: any[]) => any>(fn: F, delay: number) => {
let timeout: NodeJS.Timeout;
return (...args: Parameters<F>): Promise<ReturnType<F>> =>
new Promise((resolve) => {
clearTimeout(timeout);
timeout = setTimeout(() => resolve(fn(...args)), delay);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment