A search box can display the wrong answer even when every request succeeds.
Imagine someone types cat, pauses long enough to trigger a request, then adds an s. The request for cats finishes first. A moment later, the older cat request finishes and replaces the results. The input says one thing; the page answers something else.
A reliable implementation needs a clear rule: only work associated with the latest input may change the search UI. That rule must cover results, errors, and loading indicators.
Here, “stale” means belonging to an older input. Data freshness inside your backend or cache is a separate concern.
A. Give each mechanism one job
Three pieces work together:
- Debouncing delays starting a request while the user keeps typing.
- Cancellation stops an obsolete fetch when possible.
- A version guard decides whether completed work still owns the UI.
Debouncing alone leaves previously started requests running. Cancellation helps with those requests, but a version guard makes the UI rule explicit, including for future asynchronous work that does not support cancellation.
The subtle detail is when to advance the version: immediately when input changes. If you wait until the next request starts, an old response can still render during the debounce interval.
B. Start with a small page and an explicit response shape
<label for="query">Search articles</label>
<input id="query" type="search" autocomplete="off">
<p id="status" role="status">Type to search.</p>
<ul id="results" aria-busy="false"></ul>
<script src="search.js" defer></script>
The example expects a same-origin endpoint, /api/search?q=..., that returns JSON like this:
{"items": [{"title": "Understanding browser requests"}]}
That endpoint is an application dependency; the browser code does not implement it. An empty search response should be {"items": []}. This example treats a missing or malformed body as an error.
C. Invalidate first, then schedule
Put this first part in search.js:
const input = document.querySelector("#query");
const status = document.querySelector("#status");
const results = document.querySelector("#results");
let version = 0;
let timer;
let activeController;
function scheduleSearch() {
const mine = ++version;
clearTimeout(timer);
activeController?.abort();
activeController = undefined;
const query = input.value.trim();
results.replaceChildren();
results.setAttribute("aria-busy", "false");
if (!query) {
status.textContent = "Type to search.";
return;
}
status.textContent = "Waiting for you to finish typing…";
timer = setTimeout(() => search(query, mine), 250);
}
Every edit clears the timer, invalidates older work, and aborts the active request. Clearing the field follows the same path, so a pending request cannot refill an intentionally empty results list.
The example clears visible results immediately. If your product keeps previous results visible while loading, label which query they belong to so users do not mistake them for the current answer.
The 250 ms delay is an illustrative product choice. Adjust it for your interface. Timers also do not promise exact execution times; busy execution and browser throttling can delay them. See MDN’s timer behavior notes.
D. Guard every asynchronous outcome
Add the request function and event listener below the first block:
async function search(query, mine) {
if (mine !== version) return;
const controller = new AbortController();
activeController = controller;
status.textContent = "Searching…";
results.setAttribute("aria-busy", "true");
try {
const params = new URLSearchParams({ q: query });
const response = await fetch(`/api/search?${params}`, {
signal: controller.signal
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
if (mine !== version || controller.signal.aborted) return;
if (!Array.isArray(data?.items) ||
!data.items.every(item => typeof item?.title === "string")) {
throw new Error("Unexpected search response");
}
const rows = data.items.map(item => {
const li = document.createElement("li");
li.textContent = item.title;
return li;
});
results.replaceChildren(...rows);
status.textContent = rows.length
? `${rows.length} result${rows.length === 1 ? "" : "s"}.`
: "No results found.";
} catch (error) {
if (mine !== version || controller.signal.aborted) return;
status.textContent = "Search failed. Edit the query to try again.";
console.error("Search failed:", error);
} finally {
if (mine === version) results.setAttribute("aria-busy", "false");
if (activeController === controller) activeController = undefined;
}
}
input.addEventListener("input", scheduleSearch);
Each request gets its own controller. An aborted signal cannot be reset and reused for a later request. Passing that signal to fetch connects the request to cancellation. See MDN’s AbortSignal documentation.
URLSearchParams handles query-string encoding, including characters such as & and +. Pass the original query value rather than pre-encoding it. See MDN’s URLSearchParams reference.
There are two asynchronous boundaries here: receiving the response and reading its JSON body. Aborting can also interrupt body consumption. The guard after response.json() checks ownership before any results are rendered. MDN explains the fetch and response-body lifecycle.
Notice that the catch block performs the same ownership check. An obsolete request's failure should not replace a newer success with an error message. Cancellation caused by another edit is expected behavior and stays quiet.
Cleanup needs ownership checks too. An older finally block must not turn off a newer request's loading state or discard its controller. The version protects the loading state; the identity comparison protects the controller reference.
HTTP errors deserve separate handling. A 404 or 500 response does not automatically reject the fetch promise. This example checks response.ok, which is true for statuses 200 through 299, and throws for unsuccessful responses. See MDN’s Response.ok reference.
The response shape is validated before rendering, and titles are assigned through textContent. That keeps API-provided titles in the text path instead of interpreting them as HTML. See MDN’s textContent reference.
E. Test the order of events deliberately
Fast local responses can hide this bug. Use controlled promises and fake timers so tests choose exactly when each request completes.
Cover these scenarios:
- Rapid typing: several edits within the debounce window produce one request for the latest value.
- The debounce gap: request A starts, the input changes, and A resolves before request B starts. A must not render.
- Reversed completion: B resolves, then A resolves. B's results remain visible.
- Cleared input: an old response arrives after the field is emptied. The empty state remains.
- A stale failure: A rejects while B is loading. B keeps its loading state and controller.
- Delayed body consumption: A's response headers arrive, but its JSON body completes after a newer search. A still cannot render.
- Current failures: HTTP errors, network errors, malformed JSON, and an unexpected response shape produce an error state.
- Zero matches: an empty items array produces the no-results state rather than an error.
For the ownership tests, deliberately let the fake fetch resolve even after its signal is aborted. That exercises the guard independently from cancellation. It does not represent normal aborted-fetch behavior.
A deterministic harness for this example passed 12 checks covering those cases, encoding, and text assignment. It used fake DOM objects and fetch promises; it did not verify browser rendering, accessibility announcements, or a real server.
F. Carry the rule into production
If the component can be removed, add cleanup that advances the version, clears the timer, aborts active work, and removes its listeners.
Also check input methods used by your audience. An IME-aware version can defer requests during composition while still invalidating obsolete work immediately. If application code sets the input value directly, call the scheduling function explicitly: programmatic value changes do not trigger the normal input event. See MDN’s input event reference.
The durable rule is simple: give each search a version, and let only the current version publish an outcome. Keep that rule intact when adding caching, retries, pagination, or other asynchronous steps.