Skip to content

Instantly share code, notes, and snippets.

@erikvullings
Last active June 6, 2025 18:57
Show Gist options
  • Save erikvullings/f1b0af465f32fefdbd29348e0bea8e18 to your computer and use it in GitHub Desktop.
Save erikvullings/f1b0af465f32fefdbd29348e0bea8e18 to your computer and use it in GitHub Desktop.
Debounce a function, i.e. wait for a certain amount of time before executing the function. Often used when frequent edits would trigger a function multiple times, you can use this to wait for a certain amount of time before executing the function.
/**
* Debounce a function, i.e. wait for a certain amount of time before executing the function.
* Often used when frequent edits would trigger a function multiple times, you can use this to
* wait for a certain amount of time before executing the function.
*
* @param func The function to be debounced.
* @param delay The delay in milliseconds for the debounce.
* @returns A function that debounces the original function.
* @example const debouncedFunc = debounce(myFunction, 100); debouncedFunc(args);
*/
export const debounce = <T extends Function & ((...args: any) => any)>(
/** The function to be debounced. */
func: T,
/** The delay in milliseconds for the debounce. */
delay: number
): ((...args: Parameters<T>) => void) => {
let timeout: number | null;
return ((...args: Parameters<T>) => {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(() => {
func(...args);
}, delay);
}) as unknown as (...args: Parameters<T>) => void;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment