How To Cancel an AJAX Request in JavaScript Using the AbortController
Tags: javascript, ajax, webdev
Published: 2023-07-17 07:50:30

A  traditional website or web app always loads the entire page content on page refresh/reload. Sometimes, though, you need to just load content for a particular section of a web page.  Asynchronous JavaScript and XML (AJAX), a http approach that conducts a background network request without requiring a complete page refresh but rather in response to user interaction with a web page or app-related events, was introduced in 2006 to address this need.

### Why cancel AJAX requests?

1. Slow internet connection, cancel a request  that takes a long time to complete and retry.
2. User interaction events; when a user’s mouse enters a menu item fetch some data then cancel it if they leave the menu item before the request is complete. 
3. App related events; when the page unloads cancel all pending requests, cancel requests when offline event is fired
4. A dynamic search box where you need to fetch data as the user types the input; cancel the previous request.

### Meet Abort Controller
An `AbortController` is a Javascript built-in object that gives  developers the ability to stop asynchronous actions in their program.

 Every time a request is performed, the object instance is created, the object has `signal` property used as signal for aborting operations and a `abort` method that is called to cancel an operation.

HTTP requests made using `Fetch API` can optionally by supplied with an object that takes a signal property for cancelling a request. In case it is necessary, the process can be stopped, the signal can then be used elsewhere in the program. The `abort` method of the AbortController is used to cancel a request.

The API is quite straight forward.


Our HTML code


```javascript
<button id="cancel-btn"  
style="   padding: 0.5rem;
          background: hotpink;
          color:white;
          border-radius: 8px;
          outline: none;
          border:none;
          width: 150px;
          margin: 5rem;
        ">Initiate Request<button>
```



Our JavaScipt code



```javascript
let btn=document.getElementById("cancel-btn")
let ac = null;
let pending=false /* track when the promise is is pending and settled*/
/* we will use this function to update the DOM during http request*/
const updateDOMChanges=(message="Initiate Request")=>{
 btn.innerHTML=message;
 }

async function getUsers() {
  let url = `https://jsonplaceholder.typicode.com/posts/`;
    ac = new AbortController(); // we a new instance every time there's a request
    let signal=ac.signal
    try {
      pending=true
   updateDOMChanges("Cancel Request")  // lets update the button status
    const response = await fetch(url, { signal }); // we attach signal to our request
const payload=await response.json();
  } catch (error) { 
updateDOMChanges(error.message) 
}
  finally {
      pending=false
updateDOMChanges("Initate request again")  // lets update the button status again
    }
}

const handleButton = () => {
    // if the promise is not settled and we have an instance of abort controller, then cancel the request
    if (pending) {
        if(ac !==null) ac.abort(); 
      alert("Request cancelled")
    }else{
getUsers();
}
}

btn?.addEventListener("click",handleButton)

```


To test this code, 
1.copy the code and create an html page with a button with an id of `cancel-btn`
2. Open chrome devtools by pressing `ctrl +shift +i` then find a drop-down on the top-left corner and change from `no throttling` to `slow 3G`.
3. When the button text changes to **Cancel Request**, click it and you should see an alert that the request was cancelled.

With that knowledge, [ you can check out how to detect and cancel slow internet connect with abort controller and async/await](https://dev.to/kipyegonline/how-to-detect-slow-internet-connection-using-javascript-asyncawait-3npa)

Resources:
[MDN AbortController](https://developer.mozilla.org/en-US/docs/Web/API/AbortController)
[Dev To: How to cancel Javascript API request](https://dev.to/devsmitra/how-to-cancel-javascript-api-request-with-abortcontroller-36cm)