Asynchronous programming is essential in modern web development to provide a better user experience. However, there may be times when you need to cancel an ongoing asynchronous task, like network requests, animations, or long-running processes, to improve performance or avoid errors.
To address this need, the AbortController API was introduced in the DOM spec. The AbortController API allows you to create a controller that can be used to cancel an ongoing asynchronous task.
Prerequisites:
- Basic knowledge of JavaScript and Promises.
Step 1: Create an AbortController object
The first step is to create an AbortController object, which is done using the AbortController()
constructor. The constructor returns a new instance of the AbortController object that you can use to control asynchronous tasks.
const controller = new AbortController();
const signal = controller.signal;
Here, we’re creating a new AbortController object named “controller”. We’re also accessing its signal property, which is an object that can be passed to an asynchronous function to monitor for abort events.
Step 2: Start an asynchronous task
Next, we need to start an asynchronous task that can be aborted using the AbortController object. For this example, we’ll create a Promise that resolves after a set timeout using the setTimeout()
function.
const promise = new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => {
resolve('Async task completed!');
}, 5000);
signal.addEventListener('abort', () => {
clearTimeout(timeoutId);
reject('Async task aborted!');
});
});
Here, we’re creating a new Promise that resolves after a 5-second delay. We’re also adding an event listener to the signal object’s “abort” event. If the abort event is triggered, we’ll clear the timeout using clearTimeout()
and reject the Promise with a message.
Step 3: Handle the Promise result
After starting the asynchronous task, we can handle the Promise result using the then() method.
promise.then((result) => {
console.log(result);
}).catch((error) => {
console.log(error);
});
Here, we’re using the then()
method to log the result of the Promise when it resolves. If the Promise is rejected, we’ll log the error message using the catch()
method.
Step 4: Cancel the asynchronous task
Finally, we can cancel the ongoing asynchronous task by calling the AbortController object’s abort() method.
controller.abort();
Here, we’re calling the abort()
method of the controller object to cancel the ongoing asynchronous task. This will trigger the “abort” event, which will clear the timeout and reject the Promise with an error message.
That’s it! You’ve now learned the basics of using the AbortController API to cancel asynchronous tasks in JavaScript. Remember to handle errors and provide a better user experience by canceling unnecessary tasks.
Here is the entire process in a single code block:
// Step 1: Create an AbortController object
const controller = new AbortController();
const signal = controller.signal;
// Step 2: Start an asynchronous task
const promise = new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => {
resolve('Async task completed!');
}, 5000);
signal.addEventListener('abort', () => {
clearTimeout(timeoutId);
reject('Async task aborted!');
});
});
// Step 3: Handle the Promise result
promise.then((result) => {
console.log(result);
}).catch((error) => {
console.log(error);
});
// Step 4: Cancel the asynchronous task
controller.abort();
The only problem with this example is that we’re canceling (aborting) the task straight away (E.g. If you run this code, the task is aborted immediately.)
To better showcase how it works, here is a simple demo:
AbortController API Example
The Start button starts the timer for our 5 second async task, which also has the AbortController constructor attached to it. The Abort button uses the API to stop the task before it is completed.
Closing notes
The AbortController API is a new feature in the DOM spec that allows you to cancel asynchronous tasks that are in progress. It can be used to stop certain actions on the page from continuing, which can be useful for a number of practical reasons.
For example, when a user navigates away from a page, it’s possible that there may be ongoing network requests that are no longer needed. By using the AbortController API, you can cancel those network requests to improve performance and reduce unnecessary data usage.
Another example is when a page has animations that may be causing performance issues. By using the AbortController API, you can disable those animations when the user scrolls so that the animated portion of the page is no longer visible.
Finally, the AbortController API can be used to cancel large resources on a page like images or videos if they are still in the process of loading but aren’t needed anymore. This can save bandwidth and improve page load times.