SyntaxStudy
Sign Up
javascript

How to Debounce a Function

Limit how often a function fires using debounce — perfect for search inputs and resize events.

Debouncing delays execution of a function until after a specified time has passed since it was last called. This prevents excessive function calls during rapid events like typing or window resizing.

How It Works

  1. Every time the function is called, cancel the previous timer.
  2. Start a new timer.
  3. Only execute the function if the timer completes without being cancelled.

Use Cases

  • Search input — only search after user stops typing
  • Window resize — only recalculate layout after resize ends
  • Button clicks — prevent double submissions
Example
function debounce(fn, delay = 300) {
  let timer;
  return function(...args) {
    clearTimeout(timer);
    timer = setTimeout(() => fn.apply(this, args), delay);
  };
}

// Usage: debounce search input
const handleSearch = debounce((e) => {
  console.log('Searching for:', e.target.value);
  // make API call here
}, 400);

document.getElementById('search').addEventListener('input', handleSearch);