CodePark/ questions / Fetch, CORS & HTTP versions
START PRACTICINGPRACTICE
Frontend question · Browser & web performance › Fetch, CORS & HTTP versions

How do you cancel a fetch request or give it a timeout?

const controller = new AbortController();
fetch("/api/search?q=re", { signal: controller.signal })
  .then((res) => res.json())
  .catch((err) => {
    if (err.name === "AbortError") return;
    throw err;
  });
controller.abort();

fetch("/api/report", { signal: AbortSignal.timeout(5000) });

Use an AbortController. Pass its signal to fetch, then call controller.abort() to cancel. The promise then rejects with a DOMException named AbortError. You usually ignore this error. The same signal can cancel several requests or listeners at once.

Common uses:

  • Search-as-you-type: abort the previous request before sending a new one. Then an old, slow response can't overwrite newer results.
  • Components: abort when the component unmounts, so you don't do work for a page that is gone.

Timeouts: AbortSignal.timeout(ms) gives you a signal that aborts automatically after ms milliseconds. The rejection is then a TimeoutError. Before this existed, people combined a controller with setTimeout.

  • Pass controller.signal to fetch, then call abort() to cancel.
  • A cancelled fetch rejects with an AbortError.
  • Aborting stops old responses from overwriting newer ones.
  • AbortSignal.timeout() gives you a signal for timeouts.