SyntaxStudy
Sign Up
JavaScript Intermediate 4 min read

AbortController

Cancelling Requests

AbortController lets you cancel fetch requests and other async operations by signalling an AbortSignal.

Example
const ctrl = new AbortController();
const { signal } = ctrl;
const timer = setTimeout(() => ctrl.abort(), 5000); // 5s timeout
try {
  const res = await fetch("/api/data", { signal });
  clearTimeout(timer);
  return res.json();
} catch (e) {
  if (e.name === "AbortError") console.log("Request cancelled");
  else throw e;
}
Pro Tip

In React: call ctrl.abort() in the useEffect cleanup to cancel stale requests on unmount.