snippet · 2026-06-28 · 3 min

A typed debounce utility

A small TypeScript debounce with cancellation and an explicit limitation.

  • typescript
  • performance
  • utilities

The utility

export function debounce<Args extends unknown[]>(callback: (...args: Args) => void, delay: number) {
  let timer: ReturnType<typeof setTimeout> | undefined;
 
  const run = (...args: Args) => {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => callback(...args), delay);
  };
 
  run.cancel = () => {
    if (timer) clearTimeout(timer);
    timer = undefined;
  };
 
  return run;
}

This trailing-edge version is appropriate for lightweight UI work. It does not provide leading execution, maximum wait time, promise handling, or automatic cleanup. Cancel it during teardown when a pending callback would reference stale state.