Imagine a user types py and then python. The request for py may finish after the request for python, replacing the correct results with older ones. This is a race between responses, not a sorting problem. Cancellation reduces unnecessary work, while a sequence check protects which result is allowed to update the interface.
Track an incrementing number and create a fresh AbortController for each search. An aborted signal cannot be reset for reuse. The following function accepts rendering callbacks so its networking behavior remains separate from the page layout.
let currentController;
let sequence = 0;
async function search(query, showResults, showError) {
const requestId = ++sequence;
currentController?.abort();
const controller = new AbortController();
currentController = controller;
try {
const response = await fetch(
"/api/search?q=" + encodeURIComponent(query),
{ signal: controller.signal }
);
if (!response.ok) throw new Error("HTTP " + response.status);
const data = await response.json();
if (requestId === sequence) showResults(data);
} catch (error) {
if (error.name !== "AbortError" && requestId === sequence) {
showError(error);
}
}
}Aborting fetch tells the client to stop waiting for that operation. It does not guarantee the server never received the request or stopped processing it. This pattern is appropriate for a search read, but it should not be treated as a way to undo an order or another mutation.
If you add a loading indicator, only the current request should clear it. Otherwise an older request finishing in finally can remove the spinner while the latest request is still in progress. Apply the identity check to every state update that depends on the active request.
A debounce delays starting a search until typing pauses. It can reduce request volume but does not by itself guarantee responses arrive in order. Use it alongside cancellation when appropriate. Also decide what an empty query does: clear results, show suggestions or skip the request.
Use two controlled mock responses and resolve the second one first. Confirm that only the latest query updates the results and that cancellation does not show an error message. Add an explicit cleanup function for leaving the page.
Explore the related Code Hacker course syllabus for structured learning. Then read JavaScript Fetch: Handle HTTP Errors and Invalid JSON to connect this exercise to the next skill.
MDN AbortController provides the underlying API or technical guidance. Check the documentation for the version you use; examples here are small learning exercises rather than complete production implementations.
Found an issue with this guide? Send a correction with the article URL and your example. About our learning material.
Subscribe to Code Hacker and get hands-on access to 40+ premium courses — Ethical Hacking, Kali Linux, Metasploit, Network Hacking, Bug Bounty & more!