AbortController coordinates cancellation through an AbortSignal. Call abort() from a separate event or lifecycle path to cancel work that is no longer needed, such as a fetch request or registered event listener. section 12.1.5 section 9.2.5
Use cancellation where work can outlive the context that started it:
- Keep the active controller for a search; abort the previous request before starting another so stale results cannot replace newer ones. section 12.1.5
- For component teardown, pass one signal to listeners and fetches, then abort it when the component disconnects. section 9.2.5
- Use AbortSignal.timeout() for a deadline or AbortSignal.any() to combine cancellation conditions. Handle TimeoutError as well as AbortError; older browsers can use a timer that is cleared when the request finishes. section 12.1.5
Listing 12.2 Canceling stale search requests
const searchInput = document.getElementById("searchInput");
const resultsList = document.getElementById("results");
let activeController = null;
async function runSearch(query) {
activeController?.abort(); #1
if (!query) {
resultsList.replaceChildren();
return;
}
activeController = new AbortController();
try {
const results = await requestJSON(
`/api/search?q=${encodeURIComponent(query)}`,
{ signal: activeController.signal }
);
renderResults(results);
} catch (error) {
if (error.name === "AbortError") return; #2
renderSearchError(error);
}
}
searchInput.addEventListener("input", () => {
runSearch(searchInput.value.trim());
});
A search input cancels its active request before launching the next one and ignores AbortError while reporting other failures. section 12.1.5
