Back to Snippets
CODE

Debounce Function

Description

Delays function execution until after specified idle time, ideal for search input, autocomplete, and form validation

Code

/**
 * Debounce function implementation
 * @param fn Function to debounce
 * @param delay Idle time in milliseconds
 * @param immediate Execute immediately on first call
 * @returns Debounced function
 */
function debounce<T extends (...args: any[]) => void>(fn: T, delay: number, immediate = false): T & { cancel(): void } {
  let timeoutId: NodeJS.Timeout | null = null;

  const debounced = function(this: ThisParameterType<T>, ...args: Parameters<T>) {
    const context = this;
    const later = () => {
      timeoutId = null;
      if (!immediate) fn.apply(context, args);
    };

    const callNow = immediate && !timeoutId;
    if (timeoutId) clearTimeout(timeoutId);
    timeoutId = setTimeout(later, delay);

    if (callNow) fn.apply(context, args);
  } as T;

  debounced.cancel = () => {
    if (timeoutId) clearTimeout(timeoutId);
    timeoutId = null;
  };

  return debounced as T & { cancel(): void };
}

// Usage Example
const searchInput = document.getElementById('search-input');
const handleSearch = debounce((e: Event) => {
  console.log('Search query:', (e.target as HTMLInputElement).value);
}, 300);

searchInput?.addEventListener('input', handleSearch);

Usage

Perfect for search input autocomplete, form validation, or any scenario where you want to wait for user input to complete

Tags

PerformanceEvent HandlingDebounce