Type "javascript" into a search box and every keystroke fires an input event. If your handler calls an API on each one, you have just sent ten requests โ for "j", "ja", "jav", "java", and so on. Nine of those answers are thrown away the moment the next letter arrives, and on a slow connection the results can even arrive out of order.
Debouncing fixes this with one idea: wait until the user stops typing, then run once. This tutorial builds a debounce function from scratch, wires it into a real search input that calls an API, and covers the variations and mistakes most short guides skip.
What is debouncing?
Debouncing is a technique that delays a function call until a burst of events has calmed down. Every new event cancels the pending call and restarts the timer, and the function only runs when no new event has arrived for the full waiting time.
Picture a lift door. Each time someone walks in, the door timer resets and the door stays open a little longer. The door only closes after a full quiet stretch with nobody new arriving. A debounced function behaves the same way: each keystroke resets the timer, and the search only runs after the user has paused.
Throttling is different: it runs at most once per interval while events keep coming. Debounce waits for silence; throttle keeps a steady pace.
Step 1: Write the debounce function
The whole technique is about ten lines. It is a higher-order function: it takes a function and a delay, and returns the debounced version.
function debounce(fn, wait) {
let timeoutId;
return function (...args) {
// Cancel the call that was waiting to run.
clearTimeout(timeoutId);
// Schedule a new one. If another call arrives first, it cancels this.
timeoutId = setTimeout(() => {
fn.apply(this, args);
}, wait);
};
}
Four details make this work:
- A closure keeps
timeoutIdalive.debouncereturns a new function, and that function rememberstimeoutIdbetween calls, because the variable lives in the scope where the returned function was created. clearTimeoutcancels the previous call. Every invocation first cancels whatever was scheduled, so only the latest call can ever survive to the end of the wait....argsforwards every argument. The debounced function accepts any arguments and passes them through to the original function.fn.apply(this, args)preservesthis. If the original function is a method that usesthis, the arrow function insidesetTimeoutkeeps the right context.
This version is trailing debounce: it runs after the pause, at the end of the burst. That is the behaviour you want for search, autosave, and validation, because you only care about the final value.
Step 2: Debounce a search input
Here is the problem first. Without debounce, every keystroke sends a request:
const searchInput = document.querySelector('#search');
searchInput.addEventListener('input', (event) => {
fetchResults(event.target.value); // fires on EVERY keystroke
});
Wrap the handler and the same code sends one request per pause instead:
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);
Typing "javascript" now sends one request after the user pauses, instead of ten. The 300 millisecond wait is the usual sweet spot for search boxes: long enough to finish a word, short enough that the results still feel instant. For autosave, 800 to 1000 milliseconds feels better.
Two details in this example matter. First, the debounced function is created once, outside the listener, and the same reference is passed to addEventListener. Creating it inside the listener would build a brand-new debounced function โ with a brand-new timer โ on every keystroke, and debouncing would silently stop working.
If you are new to the fetch call itself, the patterns for GET requests, JSON parsing, and error handling are covered in our guide on how to use the JavaScript Fetch API to call a REST API โ the search example above uses exactly that shape.
Step 3: Add leading-edge calls and cancel
Sometimes you want the first call to run immediately and only the repeats to be held back. A submit button is the classic case: the first click should respond at once, but a double-click a moment later should not submit the form twice.
function debounce(fn, wait, { leading = false } = {}) {
let timeoutId;
return function (...args) {
const callNow = leading && !timeoutId;
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
timeoutId = null;
if (!leading) {
fn.apply(this, args);
}
}, wait);
if (callNow) {
fn.apply(this, args);
}
};
}
With leading: true, the first call in a burst runs right away, and further calls are ignored until the wait has passed with no new events. Note the timeoutId = null line inside the timer: it is what lets the next burst start fresh.
A cancel method is the other useful addition. It lets you stop a pending call โ for example when a component unmounts, or when the user clears the search box and you no longer want the old query to run:
function debounce(fn, wait) {
let timeoutId;
function debounced(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => fn.apply(this, args), wait);
}
debounced.cancel = () => clearTimeout(timeoutId);
return debounced;
}
Libraries such as Lodash provide all of this out of the box, with leading, trailing, and a maxWait option that forces a call after a maximum delay even if events never stop. Writing the ten-line version yourself is still worth doing once, because it teaches you the closure and timer mechanics behind every library version.
Debounce vs throttle: which one do you need?
| Debounce | Throttle | |
|---|---|---|
| Runs when | After events stop for the wait time | At most once per interval, while events continue |
| API calls for 10 keystrokes in 1 second (300 ms) | 1 | About 3 to 4 |
| Best for | Search as you type, autosave, form validation, resize finished | Scroll position, infinite scroll, mouse move, progress bars |
| Question it answers | "What is the final value?" | "What is happening right now?" |
The rule of thumb: if you only need the final value, debounce. If you need regular updates while the user is still doing something, throttle.
Three mistakes that silently break debounce
Mistake 1: Creating the debounced function inside the listener. This is the most common bug, and it fails silently โ no error, just no debouncing:
// BROKEN: a new timer on every keystroke
searchInput.addEventListener('input', (event) => {
debounce(() => fetchResults(event.target.value), 300)();
});
Every keystroke builds a fresh debounced function with its own fresh timeoutId, so nothing ever gets cancelled. Create the debounced function once and reuse it.
Mistake 2: Debouncing the wrong thing. Debounce the expensive work, not the cheap state update. In React, keep the input value updating on every keystroke so typing feels instant, and debounce only the API request.
Mistake 3: Forgetting to cancel on cleanup. In a single-page app, a pending debounced call can fire after the user has navigated away. Call debounced.cancel() in your cleanup โ the useEffect return, beforeUnmount, or wherever your framework cleans up.
Debounce in React: a small hook
In React the cleanest approach is to debounce the value, not the function. This hook delays a value until it stops changing:
import { useEffect, useState } from 'react';
export function useDebouncedValue(value, delay = 300) {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const timer = setTimeout(() => setDebouncedValue(value), delay);
return () => clearTimeout(timer);
}, [value, delay]);
return debouncedValue;
}
Use it by keeping the raw query in state for the input, and firing the API request only when the debounced query changes. The input stays instant because query updates on every key; only the request waits.
FAQ
What is debouncing in JavaScript? Debouncing delays a function until a burst of events has stopped for a set time. Each new event cancels the pending call and restarts the timer, so the function runs once, after the pause, with the latest arguments.
Should I debounce or throttle a search input? Debounce. You only need results for the query the user finishes typing, so waiting for a short pause avoids a request for every keystroke. Throttle is for things that need regular updates while they happen, like scroll position.
How long should the debounce delay be? 250 to 400 milliseconds for search boxes, 100 to 200 for resize handlers, and about 1000 for autosave. Shorter feels more responsive but saves less work; longer saves more work but can feel sluggish.
Why does debounce return a new function?
Because it needs somewhere to keep the timer between calls. The returned function closes over timeoutId, so every call to it shares the same timer and can cancel the previous one.
Is debouncing built into JavaScript?
No. You write the ten-line function above, or use one from a library such as Lodash. The pattern is just setTimeout plus clearTimeout plus a closure.
Conclusion
Debouncing is a small pattern with an outsized effect: ten lines of code turn ten wasted API requests into one, and a flickering search list into a calm one. Remember the three rules โ create the debounced function once, debounce the expensive work and not the input itself, and cancel pending calls when the work is no longer needed.


