FROMDEV

JavaScript AbortController: Cancel Fetch Requests and Async Tasks

Control JavaScript Async Work with AbortController

A slow API call, an autocomplete query that is no longer relevant, or a component that disappears while loading can leave JavaScript doing work nobody needs. JavaScript AbortController gives you a standard way to signal cancellation: pass its AbortSignal to an operation, then abort the controller when that work should stop. With Fetch, this can cancel an in-progress request; with other APIs and your own async functions, the signal can help coordinate cleanup too.

This guide shows how to cancel a fetch request, add a request timeout, handle cancellation errors, and avoid common pitfalls.

What AbortController Does

An AbortController is a small coordination object with two useful properties:

The controller does not forcibly stop arbitrary JavaScript. An operation must support the signal or check it itself. Fetch supports AbortSignal; when its request is aborted, the fetch promise rejects. The browser may stop the request or response processing, but cancellation cannot undo work a server has already completed.

Cancel a Fetch Request

Create one controller for the operation, pass its signal in the Fetch options, and abort it when needed. For example, a Cancel button can stop a request that is taking too long or is no longer useful.

const controller = new AbortController();

async function loadUser() {
  try {
    const response = await fetch("/api/user", {
      signal: controller.signal
    });

    if (!response.ok) {
      throw new Error(`HTTP error: ${response.status}`);
    }

    const user = await response.json();
    console.log(user);
  } catch (error) {
    if (error.name === "AbortError") {
      console.log("Request was cancelled.");
      return;
    }

    console.error("Could not load user:", error);
  }
}

// Call this from a cancel button or another lifecycle event:
function cancelLoad() {
  controller.abort();
}

Aborting can also reject while reading the response body, such as during response.json(). That is why the whole sequence belongs in the try block. Check response.ok separately: Fetch usually resolves for HTTP errors such as 404 or 500, rather than treating them as network failures.

Use a Fresh Controller for Each Operation

Once aborted, a signal stays aborted. Do not reuse the same controller for a later request. Create a new one for each independent operation, or create a new controller when restarting a task.

Set a Request Timeout

A timeout is a useful form of cancellation: it stops waiting after a chosen duration. In modern browsers and runtimes, AbortSignal.timeout() creates a signal that aborts automatically. Its duration is in milliseconds.

try {
  const response = await fetch("/api/report", {
    signal: AbortSignal.timeout(5000)
  });

  if (!response.ok) {
    throw new Error(`HTTP error: ${response.status}`);
  }

  const report = await response.json();
  console.log(report);
} catch (error) {
  if (error.name === "TimeoutError") {
    console.log("The request timed out.");
  } else if (error.name === "AbortError") {
    console.log("The request was cancelled.");
  } else {
    console.error("Request failed:", error);
  }
}

AbortSignal.timeout() is convenient, but check support in the browsers or runtimes you target. A timeout signal uses active time, so it may pause while a document is in the back-forward cache. The timeout rejects the local operation; it does not guarantee the server stopped processing.

Combine a Timeout with Manual Cancellation

When a request needs both a user-triggered cancel button and a timeout, combine the signals with AbortSignal.any() where supported:

const userController = new AbortController();
const timeoutSignal = AbortSignal.timeout(5000);
const signal = AbortSignal.any([
  userController.signal,
  timeoutSignal
]);

try {
  const response = await fetch("/api/report", { signal });
  const report = await response.json();
  console.log(report);
} catch (error) {
  if (signal.aborted) {
    console.log("Request stopped:", signal.reason);
  } else {
    console.error("Request failed:", error);
  }
}

// Call when the user cancels:
function cancelReport() {
  userController.abort();
}

Using signal.reason can help distinguish why a combined signal aborted. Feature-detect these newer static methods if you support older environments. A fallback is to use setTimeout() to call controller.abort(), then clear the timer in a finally block.

Use AbortSignal with Your Own Async Tasks

AbortController is not limited to Fetch. Your functions can accept a signal and cooperate by checking it or listening for its abort event. For example, a delay can reject when cancelled:

function delay(ms, { signal } = {}) {
  return new Promise((resolve, reject) => {
    if (signal?.aborted) {
      reject(signal.reason);
      return;
    }

    const timer = setTimeout(() => {
      signal?.removeEventListener("abort", onAbort);
      resolve();
    }, ms);

    function onAbort() {
      clearTimeout(timer);
      reject(signal.reason);
    }

    signal?.addEventListener("abort", onAbort, { once: true });
  });
}

const controller = new AbortController();

try {
  await delay(3000, { signal: controller.signal });
  console.log("Delay finished");
} catch (error) {
  console.log("Delay cancelled:", error);
}

// Cancel before the delay completes:
controller.abort();

For longer tasks, check signal.aborted between steps, or use an abort event listener to release resources such as timers or subscriptions. Cancellation is cooperative: code that ignores the signal will keep running.

Common Pitfalls and Trade-Offs

For example, an autocomplete should cancel the previous query when a newer one starts. Even with cancellation, it is wise to ensure only the latest query updates the results. This avoids confusing behavior if an earlier operation finishes just before cancellation takes effect.

Where AbortController Fits in Browser Code

In a component or page, abort work when it is no longer relevant: when a user cancels, navigates away, changes a search term, or removes a UI element. Keep the controller close to the code that owns the operation so its lifecycle is easy to understand.

For broader context on browser-side requests, see FromDev’s guide to AJAX books for JavaScript developers. If you are building interactive controls around loading and cancellation, this article on improving accessibility with javascript:void(0) for JavaScript links offers related guidance on accessible link behavior.

Conclusion

JavaScript AbortController makes cancellation explicit: create a controller, pass its AbortSignal to supported work, and call abort() when that work is no longer needed. Use timeouts to cap how long a request can wait, and let custom async functions cooperate with the signal. Handle cancellation separately from ordinary failures, clean up resources, and remember that stopping the client does not undo server-side work. These habits make interfaces more responsive and async code easier to manage.

Exit mobile version