AJAX - Request Cancellation Using AbortController
Introduction
Modern web applications frequently send AJAX requests to servers to retrieve or update data without reloading the page. Users often interact rapidly with web pages by typing in search boxes, clicking multiple buttons, switching tabs, or navigating between pages. In such situations, multiple AJAX requests may be sent before previous requests have completed.
If all requests continue running, they consume unnecessary network bandwidth, increase server load, and may produce outdated results. For example, if a user searches for "Computer" but quickly changes the search term to "Laptop," the earlier request for "Computer" may finish after the later request and incorrectly display outdated information.
To solve this problem, JavaScript provides the AbortController interface, which allows developers to cancel an ongoing AJAX request before it completes. This improves application performance, reduces unnecessary network traffic, and ensures that users see only the most relevant data.
What is AbortController?
AbortController is a built-in JavaScript interface that enables developers to abort one or more asynchronous operations, including AJAX requests made using the Fetch API.
It provides a mechanism for stopping requests that are no longer needed before they finish.
Instead of waiting for the server to respond, the browser immediately cancels the request.
Why Request Cancellation is Important
Consider an online shopping website.
A user types:
M
Ma
Mac
MacB
MacBo
MacBook
Each keystroke sends a new AJAX request.
Without cancellation:
Search "M"
Search "Ma"
Search "Mac"
Search "MacB"
Search "MacBo"
Search "MacBook"
Six requests reach the server.
Most of them are unnecessary because the user is only interested in the final search.
Using AbortController:
Search "M" Cancelled
Search "Ma" Cancelled
Search "Mac" Cancelled
Search "MacB" Cancelled
Search "MacBo" Cancelled
Search "MacBook" Executed
Only the latest request is processed.
Benefits of Request Cancellation
Using AbortController provides several advantages:
-
Reduces unnecessary server requests.
-
Saves network bandwidth.
-
Improves application performance.
-
Prevents outdated data from being displayed.
-
Enhances user experience.
-
Reduces browser memory usage.
-
Makes applications more responsive.
-
Supports efficient resource management.
How AbortController Works
The process follows these steps:
Step 1
Create an AbortController object.
Controller Created
Step 2
Obtain the controller's signal.
controller.signal
The signal is passed to the Fetch request.
Step 3
Start the AJAX request.
Fetch Request Started
Step 4
If the request is no longer needed,
controller.abort()
is called.
Step 5
The browser immediately stops the request.
Request Cancelled
Basic Syntax
Creating an AbortController:
const controller = new AbortController();
Getting the signal:
const signal = controller.signal;
Using it with Fetch:
fetch("products.json", {
signal: signal
});
Cancelling the request:
controller.abort();
Complete Example
const controller = new AbortController();
fetch("https://example.com/products", {
signal: controller.signal
})
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
if (error.name === "AbortError") {
console.log("Request Cancelled");
}
});
If the request is cancelled before completion:
controller.abort();
The Fetch promise rejects with an AbortError, which can be handled appropriately.
Search Box Example
Suppose a website provides live search.
Without cancellation:
User Types
A
Ap
App
Appl
Apple
Five AJAX requests are sent.
Some earlier requests may finish later than newer ones, causing outdated search results to appear.
With AbortController:
let controller;
function searchProduct(keyword)
{
if(controller)
{
controller.abort();
}
controller = new AbortController();
fetch("/search?q=" + keyword,{
signal: controller.signal
})
.then(response=>response.json())
.then(data=>display(data))
.catch(error=>{
if(error.name==="AbortError")
{
console.log("Previous Request Cancelled");
}
});
}
Every new search cancels the previous request.
Only the latest search result is displayed.
Page Navigation Example
Imagine a news website.
A user opens:
Sports
Before it loads, they click:
Technology
Without cancellation:
Sports Loading...
Technology Loading...
If the Sports request finishes last, the wrong content may appear.
With AbortController:
Sports Request Cancelled
Technology Request Continues
Only the selected page is loaded.
Auto-Suggestion Example
Search engines display suggestions while users type.
Without cancellation:
Request 1
Request 2
Request 3
Request 4
Request 5
The server processes every request.
With AbortController:
Request 1 Cancelled
Request 2 Cancelled
Request 3 Cancelled
Request 4 Cancelled
Request 5 Processed
This significantly reduces server workload.
File Download Example
Suppose a user starts downloading a report.
Before completion:
User Clicks Cancel
The application executes:
controller.abort();
The browser immediately stops downloading the file.
Timeout Example
Sometimes servers respond very slowly.
A request can be cancelled after a specified time.
const controller = new AbortController();
setTimeout(() => {
controller.abort();
},5000);
fetch("data.json",{
signal:controller.signal
});
If the server does not respond within five seconds, the request is cancelled.
Multiple Requests
Each request should generally have its own AbortController.
Example:
Product Request
Order Request
Customer Request
Each can be cancelled independently.
Alternatively, one controller can cancel multiple related requests if they all share the same signal.
Error Handling
Cancelled requests should always be handled separately.
Example:
.catch(error=>{
if(error.name==="AbortError")
{
console.log("Operation Cancelled");
}
else
{
console.log(error);
}
});
This distinguishes intentional cancellations from genuine network or server errors.
AbortController vs Ignoring Responses
Some developers ignore outdated responses instead of cancelling requests.
Ignoring responses:
Request Still Running
Server Still Processing
Bandwidth Used
AbortController:
Request Stopped
Bandwidth Saved
Resources Freed
Cancelling the request is generally more efficient because it prevents unnecessary work.
Browser Support
AbortController is supported by all modern browsers, including:
-
Google Chrome
-
Mozilla Firefox
-
Microsoft Edge
-
Safari
-
Opera
For older browsers such as Internet Explorer, AbortController is not supported. In such cases, developers need alternative approaches or polyfills.
Real-World Applications
E-Commerce Websites
Online stores cancel previous product searches as users continue typing, ensuring only the latest search results are displayed.
Social Media Platforms
Applications cancel older requests when users quickly refresh feeds, switch profiles, or browse posts, reducing unnecessary data transfers.
News Portals
When users rapidly navigate between categories, pending requests for previous pages are cancelled so that only the selected category loads.
Travel Booking Systems
As users change destinations or travel dates, previous flight or hotel search requests are cancelled to avoid displaying outdated information.
Online Banking
If users switch between account summaries, transaction history, and fund transfer pages, unnecessary requests are cancelled, improving responsiveness and conserving server resources.
Dashboard Applications
Business dashboards often refresh charts and reports automatically. If a user changes filters before the previous request finishes, the earlier request is cancelled to prevent stale data from appearing.
Advantages
-
Improves application responsiveness.
-
Reduces server workload.
-
Saves network bandwidth.
-
Prevents outdated responses from updating the interface.
-
Enhances user experience.
-
Frees browser resources.
-
Simplifies management of asynchronous operations.
-
Integrates seamlessly with the Fetch API.
Limitations
-
Primarily designed for use with the Fetch API. Older AJAX approaches such as
XMLHttpRequestuse different mechanisms for cancellation. -
Not supported in legacy browsers like Internet Explorer.
-
Cancelling a request on the client does not always stop server-side processing if the server has already begun handling the request.
-
Developers must implement proper error handling to distinguish cancelled requests from actual failures.
Best Practices
-
Create a new
AbortControllerfor each independent request. -
Cancel outdated requests before initiating new ones in dynamic interfaces.
-
Always handle
AbortErrorseparately from other errors. -
Combine request cancellation with techniques like debouncing for search inputs to further reduce unnecessary requests.
-
Use timeouts for requests that may take too long to complete.
-
Avoid cancelling requests that are critical to business operations unless there is a clear reason.
-
Test cancellation behavior under slow network conditions to ensure a smooth user experience.
Conclusion
Request cancellation using AbortController is an essential technique in modern AJAX development. It enables applications to stop unnecessary requests, conserve network and server resources, and prevent outdated information from reaching users. By integrating AbortController with the Fetch API, developers can build faster, more responsive, and user-friendly web applications that efficiently handle dynamic user interactions and asynchronous data loading.