Sub topic 12
Latency, debouncing, and feedback
This chapter assumes you know how search inputs and filter controls work, can read TypeScript and HTML, and understand basic asynchronous code (promises and fetch). Here you will learn how to keep a search interface feeling fast, and how to keep it honest when it is not.
Why latency matters in search
Search is a loop. The user types, waits, reads, and adjusts. Every delay in that loop makes the user less likely to refine the query, and more likely to abandon it.
Rough thresholds from usability research are a useful guide:
| Delay | How it feels | What to do |
|---|---|---|
| Under 100 ms | Instant | Nothing extra. Update the UI directly. |
| 100 ms to 1 s | Noticeable but fluid | Keep the old content, avoid flicker. |
| 1 s to 10 s | The user's attention drifts | Show a clear loading indicator. |
| Over 10 s | The user assumes failure | Show progress or a way to cancel, and a timeout error. |
These numbers are guidelines, not laws. Measure your own app. The point is that you design for a range of delays, because you cannot control the user's network.
Debouncing: wait for the pause
A search box can fire an event on every keystroke. Sending a request each time wastes bandwidth, loads your server, and causes the results to flicker. Debouncing delays the work until the user pauses typing.
function debounce<A extends unknown[]>(fn: (...args: A) => void, waitMs: number) {
let timer: ReturnType<typeof setTimeout> | undefined;
return (...args: A) => {
if (timer !== undefined) clearTimeout(timer);
timer = setTimeout(() => fn(...args), waitMs);
};
}
const onInput = debounce((value: string) => {
console.log("fetch suggestions for", value);
}, 200);Each call resets the timer. Only the last call in a burst runs, after waitMs of silence.
Choosing the wait time
A wait of 150 to 300 ms is a common starting range. Shorter waits feel responsive but send more requests. Longer waits save requests but make the interface feel sluggish. Pick the value by testing with real typing speed and real server latency.
Different features can use different waits:
- Suggestions: short, around 150 to 200 ms, because users expect them to track typing.
- Full results while typing (search-as-you-type): somewhat longer, because results are heavier to compute and re-render.
- Filter changes: often no debounce for checkboxes, since each click is a deliberate action. Use a debounce for sliders and text-like filters such as price range inputs.
Debounce versus throttle
Throttling runs the function at most once per interval, even while events continue. Debouncing waits until events stop. For search input, debounce is usually right because only the final text matters. Throttle fits continuous events such as dragging a range slider, where you want periodic updates during the drag.
Debouncing does not fix everything
Debouncing reduces the number of requests. It does not stop old requests from finishing late. That leads to the next problem.
Stale responses and race conditions
Network responses can arrive out of order. Suppose the user types "boo", pauses, then types "boots".
- Request A for "boo" is sent.
- Request B for "boots" is sent.
- Request B returns first, and the UI shows boots.
- Request A returns later and overwrites the UI with results for "boo".
Now the input says "boots" but the results show "boo". This is a race condition, and it is one of the most common search bugs.
Fix: cancel the previous request
The standard fix is to cancel the older request when a new one starts. The browser's AbortController does this for fetch.
let controller: AbortController | undefined;
async function search(query: string): Promise<string[] | undefined> {
controller?.abort();
controller = new AbortController();
try {
const res = await fetch(`/api/search?q=${encodeURIComponent(query)}`, {
signal: controller.signal,
});
if (!res.ok) throw new Error(`Search failed: ${res.status}`);
return (await res.json()) as string[];
} catch (err) {
if (err instanceof DOMException && err.name === "AbortError") {
return undefined; // a newer request replaced this one
}
throw err;
}
}An aborted request is not an error to show the user. Treat it as "ignore this result".
Fix: check that the response is still current
Aborting does not always work, for example when a library wraps the request. A second safeguard is to tag each request with an increasing number and ignore any response that is not the latest.
let latestId = 0;
async function searchLatestOnly(
query: string,
render: (results: string[]) => void,
): Promise<void> {
const id = ++latestId;
const res = await fetch(`/api/search?q=${encodeURIComponent(query)}`);
const data = (await res.json()) as string[];
if (id !== latestId) return; // a newer search has started
render(data);
}Use both when you can. Aborting saves work, and the id check guarantees correctness.
Feedback while waiting
Once a request is in flight, the interface must say so. Silence reads as "broken".
Match the indicator to the wait
- Under about 300 ms: show nothing new. A spinner that flashes for a fraction of a second looks worse than no spinner.
- Longer waits: show a spinner or progress text near the results.
- Long lists that will take time: show skeleton placeholders, which are gray shapes that match the layout of the result cards. They reduce the feeling of a layout jump.
A common technique is to delay the indicator itself, for example by 200 ms, so quick responses never show it.
Keep the old results visible
When the user refines a query, do not blank the results area while loading. Keep the previous results, dim them slightly, and show a loading cue. Clearing the screen causes flicker and loses the user's place in the page. Make sure dimmed results cannot be clicked into an inconsistent state, or accept that they still work until replaced.
Show what the results belong to
When results arrive, make clear which query and filters they answer. A heading such as "24 results for boots" confirms the system heard the user. This also protects against the stale response problem from the user's point of view.
Announcing changes to assistive technology
Visual feedback does not reach screen reader users. Results that update without a page load must be announced. A status region does this politely, without moving focus.
<form role="search" action="/search" method="get">
<label for="q">Search products</label>
<input id="q" name="q" type="search" autocomplete="off">
<button type="submit">Search</button>
</form>
<p role="status">24 results for "boots"</p>Update the text of the role="status" element when results change, and also when loading starts or fails. Keep messages short: "Loading results", then "24 results for boots". Do not announce every intermediate state, or the user hears a stream of chatter while typing.
Optimistic updates and perceived speed
Some work can start before the server answers.
- Update the URL and the applied-filter chips as soon as the user clicks, then fetch results. The control reacts at once even if the data follows later.
- Cache recent queries. A user who goes back to a previous search should see results immediately.
- Prefetch likely next steps, such as the first page of results for the top suggestion, only when it is cheap.
Be careful with optimistic UI for counts. If a facet count changes the moment a filter is clicked, but the numbers are guesses, users lose trust. Update counts when real data arrives.
Failure, timeouts, and retry
A slow request can become a failed one. Plan for it.
- Set a timeout. A request with no limit leaves the user watching a spinner forever.
- Show an error in the results area, in plain words, with a Retry button. Keep the user's query and filters in place.
- Do not lose input. A failed search must never clear the text box.
- For suggestions, fail quietly. If autocomplete fails, the user can still submit the query, so an error message there is noise.
function withTimeout(ms: number): AbortSignal {
const controller = new AbortController();
setTimeout(() => controller.abort(), ms);
return controller.signal;
}
async function searchWithTimeout(query: string): Promise<string[]> {
const res = await fetch(`/api/search?q=${encodeURIComponent(query)}`, {
signal: withTimeout(8000),
});
if (!res.ok) throw new Error(`Search failed: ${res.status}`);
return (await res.json()) as string[];
}Recent browsers also provide AbortSignal.timeout(ms), which does the same in one call. The helper above works where it is not available.
Common mistakes
- Debouncing but not cancelling, which leaves the race condition in place.
- Showing a spinner for every request, including fast ones, which makes the interface flicker.
- Clearing results on every keystroke.
- Treating an aborted request as an error.
- Announcing every keystroke to screen readers.
- Applying the same wait to suggestions, results, and sliders.
- Firing a search with an empty or one-character query, which is costly and rarely useful. Set a minimum length for suggestions, and decide deliberately what empty input should show.
Summary of the approach
- Debounce input, with a wait chosen per feature.
- Cancel or ignore stale requests.
- Delay and size the loading indicator to the wait.
- Keep old results visible and label the new ones.
- Announce state changes through a status region.
- Time out, show recoverable errors, and never discard the user's input.
Exercise
A user types "run", pauses, then quickly types "running shoes". The final text box says "running shoes", but the page shows results for "run". Debouncing is already in place. What is the cause, and what two changes would you make?
Show answer
The cause is a race condition. The request for "run" was sent before the second burst of typing, and its response arrived after the response for "running shoes", overwriting it. Debouncing only reduces how many requests are sent. It does not stop old ones from finishing late. Fix it by aborting the previous request with an AbortController when a new one starts, and by tagging each request with an increasing id so any response that is not the latest is ignored.
Exercise
Your search usually responds in 120 ms but sometimes takes 3 seconds. Describe how the loading feedback should behave in both cases.
Show answer
For the fast case, show no spinner, or delay the spinner by about 200 ms so it never appears, and avoid clearing the old results. For the slow case, keep the previous results visible, dim them, and show a loading indicator or skeleton once the delay has passed. Update a status region with "Loading results" for screen reader users, then announce the result count when the response arrives.