rotem-horovitz
    _hello_about-me_blog_snippets_projects_games
find me in:
privacy
← Back to snippets

debounce

Delay invoking a function until a quiet period has passed since the last call. Great for input handlers and resize listeners.

May 20, 2026
utilityperformancetiming

debounce wraps a function so that repeated calls reset a timer; the wrapped callback only fires once the caller has gone quiet for delay milliseconds. Typical uses: search-as-you-type inputs, window resize handlers, autosave triggers.

export function debounce<T extends (...args: unknown[]) => void>(
	fn: T,
	delay: number,
): (...args: Parameters<T>) => void {
	let timerId: Nullable<ReturnType<typeof setTimeout>> = null;
	return (...args: Parameters<T>) => {
		if (timerId !== null) clearTimeout(timerId);
		timerId = setTimeout(() => {
			fn(...args);
		}, delay);
	};
}

Notes

  • The generic constraint T extends (...args: unknown[]) => void keeps the argument types intact while enforcing a void return — the caller's return value is discarded by design.
  • Each call clears the previous timer, so only the last invocation in a burst executes.