Skip to content

Instantly share code, notes, and snippets.

@FaberVitale
Created September 19, 2024 06:36
Show Gist options
  • Save FaberVitale/08a925b4c546438a374bb261ceadbd7b to your computer and use it in GitHub Desktop.
Save FaberVitale/08a925b4c546438a374bb261ceadbd7b to your computer and use it in GitHub Desktop.
debounce
export interface Debounced<F extends (...arg: any[]) => any> {
(...args: Parameters<F>): void;
clear(): void;
}
/**
* Returns a function that executes `func` until after `wait`
* milliseconds have elapsed since the last time the debounced function was
* invoked.
*
* The debounced function provides a `clear` handle to cancel a pending execution.
*/
export function debounce<Func extends (...arg: any[]) => any>(
func: Func,
waitMs: number
): Debounced<Func> {
if (typeof func != 'function') {
throw new TypeError('debounce: input is not a function');
}
let timeoutRef: ReturnType<typeof setTimeout> | undefined;
const clear = (): void => {
if (timeoutRef) {
clearTimeout(timeoutRef);
timeoutRef = undefined;
}
};
const output = function (this: unknown, ...args: Parameters<Func>) {
clear();
timeoutRef = setTimeout(() => {
func.apply(this, args);
}, waitMs);
};
(output as Debounced<Func>).clear = clear;
return output as Debounced<Func>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment