TypeScript

Debounce (typed)

admin by @admin ADMIN
Jun 16, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Wait until the caller stops invoking for `delay` ms, then call the function with the most recent arguments. The TS version preserves the original signature so the returned function has the same parameters.
TypeScript
Raw
export function debounce<Args extends unknown[]>(
  fn: (...args: Args) => void,
  delay: number,
): (...args: Args) => void {
  let timer: ReturnType<typeof setTimeout> | null = null;
  return (...args) => {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => fn(...args), delay);
  };
}

const onSearch = debounce((q: string) => {
  fetch(`/search?q=${encodeURIComponent(q)}`);
}, 300);

input.addEventListener('input', e => onSearch((e.target as HTMLInputElement).value));
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.