Debounce is a technique that delays running a function until an event has stopped firing for a set amount of time. For a search box, instead of calling the API after every character the user types, you wrap the API call in a 300ms debounce — the API is only called once the user has stopped typing for a full 300ms. This cuts dozens of wasted requests down to one, and it works for every search box, filter, and auto-saving form.

The Problem

Suppose a search box calls the API right inside the input event. The user types “linhfish” — 8 characters, 8 requests flying off almost at once. The server has to process 7 requests that are already outdated, and the request for “l” may return after the request for “linhfish” and overwrite the correct results with wrong ones. This is called a race condition at the UI layer, and it happens with every input form that calls an API directly: autocomplete, table filters, username checks.

searchInput.addEventListener("input", (event) => {
fetch(`/api/search?q=${event.target.value}`)
.then((res) => res.json())
.then(renderResults);
});

The Solution

Debounce solves it with a single timer: each time the event fires, cancel the old timer and set a new one. Only when no event has fired for 300ms does the function actually run. The debounce function below works for any function, preserving this and its arguments through ...args and apply.

function debounce(fn, delay = 300) {
let timerId;
return function (...args) {
clearTimeout(timerId);
timerId = setTimeout(() => fn.apply(this, args), delay);
};
}
const searchApi = debounce(async (query) => {
const res = await fetch(`/api/search?q=${encodeURIComponent(query)}`);
renderResults(await res.json());
}, 300);
searchInput.addEventListener("input", (event) => {
searchApi(event.target.value.trim());
});

With this code, typing “linhfish” creates just one request, sent after your hands leave the keyboard for 300ms. The 300ms figure is a practical balance point: shorter and requests still get spammed, longer and the search box feels sluggish. If you want an immediate response on the first keystroke and debounce only the ones after, add a leading option — lodash.debounce supports it out of the box.

Apply It to Your Project

Apply it to your project right away: wrap the API function of your search box, autocomplete, and filters in a 300ms debounce; use 500–1000ms for auto-saving drafts. For scroll and resize events, debounce is the wrong choice — use throttle, because you need continuous updates while scrolling, not a wait until scrolling ends. One last note: debounce only delays calling the function; it doesn’t cancel a request already in flight — if an old result can still arrive late, combine it with AbortController to cancel the previous request.

Related Posts

FAQ

How is debounce different from throttle?

Debounce waits until the event has fully stopped, then runs once; throttle limits execution to at most once per time window — for example, once every 200ms. Search boxes use debounce; scroll and resize use throttle.

What delay should I use, in milliseconds?

Search and autocomplete: 200–300ms. Auto-saving drafts: 500–1000ms. Test with real users: if it feels slow, drop 50ms; if the server is still overloaded, add 100ms.

Can debounce cancel a request already in flight?

No. Debounce only delays when the function is called; a request already sent keeps running. To cancel the old request, combine it with AbortController as the fetch article explains.

How do I use debounce in React or Vue?

Wrap the debounced function in useMemo (React) or create it once in setup (Vue) so you don’t create a new function on every render — otherwise the timer resets constantly and the function never runs. Or use lodash.debounce, which already ships cancel and flush methods.

💬 Have you tried this in your own project? If you hit an error or have a shorter way, leave a comment below — I read them all and will fold the good ideas into the post.

References