liveBook · Manning

AbortController

As explained in Vanilla Web

AbortController is a browser interface for signaling cancellation of asynchronous operations such as fetch requests and event listeners.

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

How Vanilla Web covers it

How deep it goes
Demonstrates controller ownership, abort triggers, timeout helpers, combined signals, and cancellation error handling through concrete patterns.
Examples
Shows canceling overlapping search requests, timing out fetches, and cleaning up component listeners and requests.
What it assumes
Assumes familiarity with fetch requests, event listeners, and component lifecycle callbacks.
What you can do after
Apply cancellation to prevent stale search results and to release component-owned requests and listeners.
How it connects
Connects AbortSignal to fetch, event listeners, custom elements, and stale-request handling.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Vanilla Web. The section links point to the parts of the book it draws on.