JavaScript Advanced DOM & Async · 8 min read

AbortController for fetch

Lesson 22 of 38 in the JavaScript learning path.

How do I cancel a fetch when the user types again?

An AbortController gives you a signal you can pass to fetch. Calling abort marks that signal aborted and rejects the fetch with a DOMException named AbortError. Create a new controller for each search. When the learner types again, abort the previous controller before the next request starts.

A cancelled search is not a failure to show in the results list. Check error.name before you write an error message, and ignore a response whose controller is no longer the current one. Abort does not roll back work the server already finished. It stops this page from using that body. Pair it with a short debounce so a request does not open on every key.

Syntax & Parameters

Syntax
fetch(url, { signal: controller.signal })

Example

Interactive preview available
app.js
const note = document.createElement("p");
note.id = "search-note";
note.textContent = "Type at least 2 letters";

const input = document.createElement("input");
input.id = "lesson-search";
input.setAttribute("aria-label", "Search lessons");

const results = document.createElement("ul");
results.id = "search-results";

let controller = null;
let debounceTimer = 0;

async function searchLessons(query, signal) {
  if (signal.aborted) {
    throw new DOMException("The operation was aborted.", "AbortError");
  }
  await new Promise((resolve, reject) => {
    const timerId = window.setTimeout(() => resolve(), 350);
    signal.addEventListener("abort", () => {
      window.clearTimeout(timerId);
      reject(new DOMException("The operation was aborted.", "AbortError"));
    }, { once: true });
  });
  const payload = JSON.stringify({
    matches: [query + " routes", query + " forms"]
  });
  const blob = new Blob([payload], { type: "application/json" });
  const url = URL.createObjectURL(blob);
  try {
    const response = await fetch(url, {
      method: "GET",
      headers: { Accept: "application/json" },
      signal
    });
    if (!response.ok) {
      throw new Error("Search failed with status " + String(response.status));
    }
    return response.json();
  } finally {
    URL.revokeObjectURL(url);
  }
}

function startSearch(query) {
  if (controller !== null) {
    controller.abort();
  }
  controller = new AbortController();
  const active = controller;
  note.textContent = "Searching for " + query;
  searchLessons(query, active.signal).then((payload) => {
    if (active !== controller) {
      return;
    }
    results.replaceChildren();
    for (const title of payload.matches) {
      const item = document.createElement("li");
      item.textContent = title;
      results.append(item);
    }
    note.textContent = "Showing " + query;
  }).catch((error) => {
    if (active !== controller) {
      return;
    }
    if (error.name === "AbortError") {
      return;
    }
    note.textContent = error.message;
  });
}

input.addEventListener("input", () => {
  window.clearTimeout(debounceTimer);
  const query = input.value.trim();
  if (query.length < 2) {
    if (controller !== null) {
      controller.abort();
      controller = null;
    }
    results.replaceChildren();
    note.textContent = "Type at least 2 letters";
    return;
  }
  debounceTimer = window.setTimeout(() => {
    startSearch(query);
  }, 200);
});

document.body.append(note, input, results);

Expected Output

Type at least 2 letters

After a pause on the query ro:
Searching for ro
Showing ro
ro routes
ro forms

A newer keystroke aborts the previous controller. That older payload does not replace the list.

Line-by-Line Walkthrough

  1. The note, the input, and the results list are created in the script so there is a place to type.
  2. searchLessons rejects immediately when the signal is already aborted.
  3. The 350ms wait also rejects with AbortError, and it clears its timer so a cancelled wait does not continue.
  4. fetch then loads a JSON blob and receives the same signal, so a later abort still cancels the request.
  5. The blob URL is revoked in finally on success and on failure.
  6. A response that is not ok throws an Error with the status. That name is not AbortError.
  7. startSearch aborts the previous controller and replaces it before the new search begins.
  8. The then handler returns when its controller is no longer current, so an older payload cannot paint.
  9. AbortError is ignored. Any other error while this search is still current is written to the note.
  10. Each key clears the 200ms debounce. Fewer than 2 characters aborts the current search and clears the list.

Common Pitfalls & Security

Abort stops the browser from delivering the body to this call. The server may already have done the work. Do not use abort as an authorization mechanism.

  • One controller cannot be reused after abort. Create a new AbortController for the next search.
  • Treating AbortError like a server failure flashes a red error while the visitor is still typing.
  • Forgetting the current-controller check lets a slow response paint over a newer result if abort loses a race.
  • Aborting does not clear a debounce timer. Clear the timer on each input or an old query can still start.
  • Passing a signal from a page-level controller into an unrelated request cancels too much when you abort.
  • A search request still needs the same auth and encoding rules as any other fetch. The signal does not add them.

Best Practices & Modern Standards

Keep the controller next to the feature that owns the request, not in a global that every widget shares. Abort on the event that makes the old request useless: a new query, a closed dialog, or a route change.

Debounce the start, but abort immediately when the field becomes too short to search. Check response.ok before you read JSON. Ignore AbortError in the catch, and log or show every other failure.

Real-World Use

The lesson search waits 200ms after the last key, then fetches matches. If the learner types again, the previous controller aborts and only the latest query is allowed to fill the list. A slow "route" response cannot overwrite a newer "forms" response.

Frequently Asked Questions

Which error name means a cancel?

AbortError. fetch rejects with a DOMException of that name when the signal aborts. A network failure has a different name.

Does abort stop the server?

It tells the browser to drop the response. The server may still finish the request. Do not rely on abort to undo a write that already happened.

Can I reuse a controller after abort?

No. signal.aborted stays true. Construct a new AbortController for the next fetch.

Where do I pass the signal?

Pass it as the signal option on fetch. Any other API that accepts an AbortSignal, such as addEventListener, can share that same signal.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…