← Back to snippets
typescriptutilityperformanceevents

Debounce Function

Classic debounce utility with TypeScript generics. Perfect for search inputs and resize handlers.

Code

function debounce<T extends (...args: unknown[]) => unknown>(
  fn: T,
  delay: number
): (...args: Parameters<T>) => void {
  let timeoutId: ReturnType<typeof setTimeout>;

  return function (this: unknown, ...args: Parameters<T>) {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => fn.apply(this, args), delay);
  };
}

// Usage
const debouncedSearch = debounce((query: string) => {
  console.log('Searching:', query);
}, 300);

input.addEventListener('input', (e) => {
  debouncedSearch(e.target.value);
});

Variations

With immediate option

function debounce<T extends (...args: unknown[]) => unknown>(
  fn: T,
  delay: number,
  immediate = false
) {
  let timeoutId: ReturnType<typeof setTimeout> | null;

  return function (this: unknown, ...args: Parameters<T>) {
    const callNow = immediate && !timeoutId;

    if (timeoutId) clearTimeout(timeoutId);

    timeoutId = setTimeout(() => {
      timeoutId = null;
      if (!immediate) fn.apply(this, args);
    }, delay);

    if (callNow) fn.apply(this, args);
  };
}