DEV Community

Raja Hunain
Raja Hunain

Posted on

Debounce in JavaScript: The 10-Line Fix That Stops Your Search Box Firing on Every Keystroke

Type "javascript" into a search box and your code fires an input event for every letter. If the handler calls an API each time, that is ten requests for one word — nine of them for queries nobody will ever see. On a slow connection the answers can even arrive out of order, so the list shows results for "jav" under the finished word "javascript".

The fix is called debouncing: wait until the user stops typing, then run once. The whole technique is about ten lines.

The function

function debounce(fn, wait) {
  let timeoutId;

  return function (...args) {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => {
      fn.apply(this, args);
    }, wait);
  };
}
Enter fullscreen mode Exit fullscreen mode

It is a higher-order function. It takes your function and a delay, and returns a new function that is the debounced version. Every call cancels the pending timer and starts a fresh one, so only the last call in a burst survives. The closure over timeoutId is what makes that possible — without it there would be nowhere to store the pending timer.

Wiring it into a search input

const searchInput = document.querySelector('#search');

async function fetchResults(query) {
  const response = await fetch(`/api/search?q=${encodeURIComponent(query)}`);
  renderResults(await response.json());
}

const debouncedSearch = debounce((event) => {
  fetchResults(event.target.value);
}, 300);

searchInput.addEventListener('input', debouncedSearch);
Enter fullscreen mode Exit fullscreen mode

Typing "javascript" now sends one request after the user pauses instead of ten. 300 milliseconds is the usual sweet spot for search: long enough to finish a word, short enough that results still feel instant. For autosave I use 800 to 1000 milliseconds.

The mistake that breaks it silently

Create the debounced function once, outside the listener. This is the bug I see most often:

// BROKEN: a new timer on every keystroke
searchInput.addEventListener('input', (event) => {
  debounce(() => fetchResults(event.target.value), 300)();
});
Enter fullscreen mode Exit fullscreen mode

Every keystroke builds a fresh debounced function with its own fresh timer, so nothing ever gets cancelled. No error, no warning — debouncing just quietly does nothing.

Two useful variations

Leading edge. Sometimes the first call should run immediately and only the repeats should be held back — a submit button is the classic case. Pass { leading: true } and the first call in a burst runs at once, while the rest wait for the quiet stretch.

Cancel. Add a cancel method that clears the timer, and call it when the work is no longer needed — for example when a component unmounts or the user clears the search box.

Debounce vs throttle

If you only need the final value, debounce. If you need regular updates while the user is still doing something, throttle. A search box needs the final query, so it gets debounce. A scroll handler moving a progress bar needs to know where the user is right now, so it gets throttle.

I wrote the full version of this with the leading-edge code, the cancel method, a React useDebouncedValue hook, and a FAQ here: https://rajadevsolutions.online/blog/how-to-debounce-in-javascript

Ten lines, one closure, one timer — and your search box stops shouting at your server.

Top comments (0)