Eliminating Unnecessary Work

Imagine a search field that fires an API request on every single keystroke. A fast typist might send 10+ requests per second, hammering your server with mostly useless intermediate queries.

The Debounce Principle

Wait for the user to pause before acting. If a new action happens while you're waiting, reset the timer.

function debounce(fn, delayMs) {
  let timeoutId;
  return function(...args) {
    clearTimeout(timeoutId);  // Cancel any previous pending call
    timeoutId = setTimeout(() => {
      fn.apply(this, args);   // Execute only after the delay
    }, delayMs);
  };
}

// Usage: only fire the search after the user stops typing for 500ms
const searchInput = document.querySelector('#search');
searchInput.addEventListener('input', debounce(fetchResults, 500));

Visualizing the Behavior

User typing: A → B → C → [pause 500ms] → D
API calls:                                → fetchResults('ABCD')
Note

Debounce is perfect for: search fields, live form validation, autosave, and any situation where you want to react only to a " settled " final state.