Debounce and request cancellation
Wait for a pause in typing before you ask the server, then make sure only the answer to the newest query reaches the screen: cancel the older request, or ignore its answer.
What it is
Search as you type has two separate problems. The first is volume: someone typing a word produces an event per key, and you do not want a request per key. The second is order: requests that overlap can come back in any order, so an answer for an older query can land after the newer one and overwrite it. Debouncing solves the first. Cancelling or ignoring stale requests solves the second. You need both, because a pause in the middle of a word still lets an older request overlap a newer one.
Debounce means dropping calls that come too close together and running one call once they stop. Each new call restarts the wait, and the work usually runs on the trailing edge, after the last call. Throttle is its cousin: it runs the work at most once per interval while calls keep coming, so something that tracks a scroll position keeps moving instead of waiting for the scroll to end.
Cancelling uses an AbortController. You pass its signal to fetch, and calling abort() stops the request: the fetch promise rejects with a DOMException named AbortError, and if the response already arrived, reading its body rejects the same way. A signal works once. After it aborts, any fetch given that same signal rejects straight away, so you make a new controller for every request.
let timer: ReturnType<typeof setTimeout> | undefined;
let controller: AbortController | undefined;
let latest = 0;
function onInput(text: string) {
clearTimeout(timer);
controller?.abort(); // whatever is in flight is for older text
const query = text.trim();
if (query.length < 2) {
showSuggestions([]); // clear now, not after the wait
return;
}
timer = setTimeout(() => void search(query), 250);
}
async function search(query: string) {
controller?.abort(); // the older request is stale now
controller = new AbortController();
const id = ++latest;
showLoading();
try {
const res = await fetch(`/search?q=${encodeURIComponent(query)}`, { signal: controller.signal });
if (!res.ok) throw new Error('search failed');
const { results } = await res.json();
if (id === latest) showSuggestions(results);
} catch (err) {
if (err instanceof DOMException && err.name === 'AbortError') return; // we cancelled it
if (id === latest) showError();
}
}When to use it
Debounce anything that turns typing into a network request or other expensive work: suggestions, search as you type, checking whether a username is free. A common starting wait is 200 to 300 ms. Match it to the server: about 200 ms when the server answers in under 100 ms, about 350 ms when it takes 300 ms or more. A fixed 500 ms is a listed mistake because it feels laggy.
Cancel or ignore older requests whenever a newer query replaces an older one: suggestions, filters, tabs that each load data. Prefer abort() because the browser stops waiting and stops reading the body. Fall back to numbering requests, latest wins, when the call you were given has no way to take a signal. Comparing the time each answer arrives is the weak version: arrival order is exactly what goes wrong.
Decide what the person sees while they wait. The typed letter must paint right away: Interaction to Next Paint counts from the key press to the next frame, and 200 ms or less is good. Results arrive whenever the network answers, so show a loading state in the list, remove it when the request resolves or aborts, clear the list at once when the box empties, and show an error state when a request fails. A screen reader user hears the result count through a polite live region that exists before the first update.
When not to
Do not debounce work that is cheap and local, such as filtering a short list already in memory: the wait only makes the box feel slower. If the cost is rendering a large list rather than a request, React offers useDeferredValue, which has no fixed delay and lets a new keystroke interrupt a render. It does not cut network requests on its own, so pair it with a debounce when requests are the cost.
Use throttle, not debounce, when the screen has to keep up during a continuous stream of events, such as moving something as the page scrolls. A debounce would freeze it until the stream stops.
Compared
| Technique | What it does | Reach for it when | What it costs |
|---|---|---|---|
Debounce | Waits until calls stop for a set time, then runs once | Typing drives a request | Adds the wait to every query |
Throttle | Runs at most once per interval while calls keep coming | The screen must follow a stream, like scrolling | Still runs many times during a long stream |
Abort the older request |
| The data call accepts a | A new controller per request |
Number requests, latest wins | Applies an answer only if its number is the newest | The call cannot be cancelled | The stale request still runs to the end |
Defer rendering | React's | Rendering, not the network, is slow | Does not reduce requests by itself |
In a picture
Step 1 of 3
A pause sends the first query
Someone types l, a, p. Each key restarts the timer, so nothing is sent until they pause. Then one request goes out, for lap.