Skip to main content

Debounce Function

Performance2 functions

Utility Overview

Details

Delays function execution until a specified wait time has elapsed since the last call, optimizing performance for frequent events

Category:Performance
Functions:debounce, debounceImmediate
Concepts:
closureshigher-order functionsevent optimizationperformance

Implementation

debounce

Time: O(1) | Space: O(1)
export function debounce<T extends DebouncableFunction>(
  func: T,
  wait: number
): (...args: Parameters<T>) => void {
  if (typeof func !== 'function') throw new Error("First argument must be a function");
  if (!Number.isInteger(wait) || wait < 0) throw new Error("Wait time must be a non-negative integer");
  
  let timeout: NodeJS.Timeout | null = null;

  return (...args: Parameters<T>) => {
    if (timeout) {
      clearTimeout(timeout);
    }
    timeout = setTimeout(() => {
      func(...args);
    }, wait);
  };
}

// Alternative implementation with immediate execution option

Usage Examples

Basic debounce for search input

const debouncedSearch = debounce(handleSearch, 300);
input.addEventListener('input', (e) => debouncedSearch(e.target.value));

// Function will only execute 300ms after the last input event

Optimize window resize events

const debouncedResize = debounce(updateLayout, 200);
window.addEventListener('resize', debouncedResize);

// Layout updates only after resize events stop for 200ms

Immediate execution with debounce

const debouncedSubmit = debounceImmediate(submitForm, 500, true);
button.addEventListener('click', debouncedSubmit);

// Executes immediately, then prevents subsequent calls for 500ms

API rate limiting

const debouncedApiCall = debounce(fetchData, 1000);
searchInput.addEventListener('input', () => debouncedApiCall(query));

// API calls limited to maximum once per second