🛑 AbortController in JavaScript – Complete Tutorial

AbortController is a built-in JavaScript API that allows you to cancel asynchronous operations such as fetch(), streams, and other APIs that support AbortSignal. It helps prevent unnecessary network requests and improves application performance.

📌 What is AbortController?

AbortController creates a controller object that can abort one or more asynchronous operations. It works together with anAbortSignal, which is passed to APIs that support cancellation.

>>"AbortController provides a standard way to cancel asynchronous tasks in JavaScript."

💡 Why Use AbortController?

  • 🛑 Cancel unnecessary network requests
  • ⚡ Improve application performance
  • 🔍 Stop previous search requests while typing
  • 📱 Prevent memory leaks in single-page applications
  • ⏱️ Implement request timeouts

🏗 Creating an AbortController

Create Controller

const controller = new AbortController();

📡 Getting the AbortSignal

The controller provides a signal that is passed to APIs supporting cancellation.

Access Signal

const signal = controller.signal;

🌐 Using AbortController with Fetch

Fetch with Signal

const controller = new AbortController();

fetch("https://api.example.com/users", {
  signal: controller.signal
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error));

🛑 Cancelling a Request

Call abort() to cancel the operation.

Abort Request

controller.abort();

❌ Handling Abort Errors

When a fetch request is aborted, the promise rejects with anAbortError.

Handle AbortError

fetch("/users", {
  signal: controller.signal
})
.catch(error => {

  if (error.name === "AbortError") {
    console.log("Request cancelled");
  }

});

⏱ Request Timeout Example

You can combine AbortController withsetTimeout() to cancel slow requests.

Timeout Example

const controller =
  new AbortController();

setTimeout(() => {
  controller.abort();
}, 5000);

fetch("/users", {
  signal: controller.signal
});

🔍 Cancel Previous Search Requests

A common use case is live search, where previous requests are cancelled when the user types a new query.

Live Search

let controller;

async function search(query) {

  if (controller) {
    controller.abort();
  }

  controller =
    new AbortController();

  try {

    const response =
      await fetch(
        "/search?q=" + query,
        {
          signal:
            controller.signal
        }
      );

    const data =
      await response.json();

    console.log(data);

  } catch (error) {

    if (
      error.name !==
      "AbortError"
    ) {
      console.error(error);
    }

  }

}

📢 Listening for Abort Events

The AbortSignal emits an abort event when cancellation occurs.

Abort Event

const controller =
  new AbortController();

controller.signal.addEventListener(
  "abort",
  () => {
    console.log("Operation aborted");
  }
);

controller.abort();

📊 AbortSignal Properties

PropertyDescription
abortedtrue if the signal has been aborted.
reasonThe reason provided when aborting (supported in modern browsers).

🛠 Complete Example

Fetch with Cancel Button

const controller =
  new AbortController();

fetch("/users", {
  signal:
    controller.signal
})
.then(response =>
  response.json()
)
.then(data => {
  console.log(data);
})
.catch(error => {

  if (
    error.name ===
    "AbortError"
  ) {
    console.log(
      "Fetch cancelled"
    );
  }

});

document
  .getElementById("cancel")
  .onclick = () => {
    controller.abort();
  };

HTML

<button id="cancel">
Cancel Request
</button>

📊 AbortController vs Ignoring the Response

FeatureAbortControllerIgnore Response
Stops Network Request✅ Yes (where supported)❌ No
Saves Bandwidth✅ Yes❌ No
Prevents Unwanted Updates✅ Yes⚠️ Partially
Modern API✅ Yes❌ Not a cancellation mechanism

⚠️ Limitations

  • 🌐 Only works with APIs that support AbortSignal.
  • 🛑 Aborting after an operation has already completed has no effect.
  • 🔄 A controller cannot be reused once it has been aborted; create a new AbortController for each independent operation.

Note

Modern browser APIs such as fetch(), many stream operations, and some other web APIs support AbortSignal. Always check the API documentation to confirm cancellation support.

✅ Best Practices

  • 🔍 Cancel previous search requests in live search interfaces.
  • ⏱️ Use request timeouts for slow network operations.
  • 🧹 Abort requests when components or pages are no longer active.
  • ❌ Handle AbortError separately from genuine network errors.
  • 🆕 Create a fresh AbortController for each request or logical group of requests.

🎯 Summary

AbortController provides a standard way to cancel asynchronous operations in JavaScript. It is commonly used with the Fetch API to stop unnecessary requests, implement timeouts, and improve responsiveness in modern web applications. By pairing an AbortController with itsAbortSignal, you gain fine-grained control over cancellable operations.