Skip to content

Instantly share code, notes, and snippets.

@cap340
Last active October 15, 2025 03:47
Show Gist options
  • Save cap340/49c7d131e6d9d11679c4b940e6e95881 to your computer and use it in GitHub Desktop.
Save cap340/49c7d131e6d9d11679c4b940e6e95881 to your computer and use it in GitHub Desktop.
A typescript simple debounce function
/**
* @example
* ```ts
* const textInput = document.querySelector<HTMLInputElement>('input[type="text"]');
* textInput.addEventListener('keydown', debounce(fetchSuggestions, 300));
* ```
*
* @param {T} callback - The callback function to be debounced.
* @param number delay - the delay in milliseconds
*/
export const debounce = <T extends unknown[]>(
callback: (...args: T) => void,
delay: number,
): ((...args: T) => void) => {
let timeoutTimer: ReturnType<typeof setTimeout>;
return (...args: T) => {
clearTimeout(timeoutTimer);
timeoutTimer = setTimeout(() => {
callback(...args);
}, delay);
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment