Open Playground
JS AsyncLesson #248

Asynchronous AbortController

The AbortController Object lets you cancel asynchronous operations.

The AbortController Object lets you cancel asynchronous operations.

It is commonly used to cancel fetch() requests.

Canceling unnecessary operations can improve performance and make applications more responsive.

Share

Why Cancel a Request?

Sometimes an asynchronous operation is no longer needed.

Examples include:

  • The user clicks a Cancel button.
  • The user starts another search.
  • The user leaves the page.
  • A request takes too long.

In these situations, you can cancel the operation instead of waiting for it to finish.


Creating an AbortController

Create an AbortController with the new keyword.

Example

Example Code

javascript
Try it Yourself
const controller = new AbortController();

The Abort Signal

An AbortController provides an AbortSignal.

The signal is passed to an asynchronous operation.

The operation receives the signal and stops.

Example

Example Code

javascript
Try it Yourself
const controller = new AbortController();

const signal = controller.signal;

Canceling a Fetch Request

Pass the controller's signal to fetch().

Example

Example Code

javascript
Try it Yourself
const controller = new AbortController();

fetch("largefile.txt", {

  signal: controller.signal

});

Aborting a Request

Call abort() to cancel the operation.

Example

Example Code

javascript
Try it Yourself
controller.abort();

Complete Example

Example

Example Code

javascript
Try it Yourself
const controller = new AbortController();

// Async function to download a file

async function loadFile(file) {

  try {

    const response = await fetch(file, {

      signal: controller.signal

    });

    myDisplayer(await response.text());

  } catch(err) {

    if (err.name == "AbortError") {

      myDisplayer("Download canceled");

    }

  }

}

// Call the async function

loadFile("fetch.txt");

Cancel with a Button

A request can be canceled when the user clicks a button.

Example

Example Code

html
Try it Yourself
**Start Download

 Cancel Download

Create a New Controller for Each Request

Once an AbortController has been aborted, it cannot be reused.

Create a new controller for each new request.


Cancel the Previous Request

Search applications often cancel an earlier request before starting a new one.

Example

Example Code

javascript
Try it Yourself
let controller;

async function search(text) {

  if (controller) {

    controller.abort();

  }

  controller = new AbortController();

  try {

    const response = await fetch(

    "/search?q=" + text,

    {signal: controller.signal}

  );

    console.log(await response.text());

  }

  catch(err) {

    if (err.name != "AbortError") {

      console.log(err);

    }

  }

}

Example

Example Code

javascript
Try it Yourself
User types:

c
ca
cat
cats

↓

Only the last request finishes.

Cancel After a Timeout

You can combine timers with AbortController)=.

Example

Example Code

javascript
Try it Yourself
const controller = new AbortController();

setTimeout(function(){

  controller.abort();

},5000);

await fetch(url,{

  signal: controller.signal

});

Common Mistakes

Forgetting to pass the signal.

Wrong:

Example Code

javascript
Try it Yourself
fetch(url);

Right:

Example Code

javascript
Try it Yourself
fetch(url);

Reusing a canceled controller.

Remember to create a new controller.

Treating AbortError as a Failure

An aborted request is often expected.

Handle it separately.

Example

Example Code

javascript
Try it Yourself
if (err.name == "AbortError") {

  return;

}

Browser Support

AbortController is supported by all modern browsers.

It is widely used together with the Fetch API.


AbortController Checklist

  • Create a new controller for each new request
  • Create it with new AbortController()
  • Pass controller.signal to fetch()
  • Call abort() to cancel the request
  • Handle AbortError in a catch block

Interactive Code Examples

JS Example 1

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
const controller = new AbortController();

JS Example 2

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
const controller = new AbortController();

const signal = controller.signal;

JS Example 3

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
const controller = new AbortController();



fetch("largefile.txt", {

  signal: controller.signal

});

JS Example 4

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
controller.abort();

JS Example 5

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
const controller = new AbortController();



// Async function to download a file

async function loadFile(file) {

  try {

    const response = await fetch(file, {

      signal: controller.signal

    });



    myDisplayer(await response.text());



  } catch(err) {

    if (err.name == "AbortError") {

      myDisplayer("Download canceled");

    }

  }

}



// Call the async function

loadFile("fetch.txt");

JS Example 6

html
Try it Yourself
Interactive runnable JavaScript example from EA Academy.
Live Output Preview: