fetch
now supports a signal
parameter as of 20 September 2017, but not
all browsers seem support this at the moment.
2020 UPDATE: Most major browsers (Edge, Firefox, Chrome, Safari, Opera, and a few others) support the feature, which has become part of the DOM living standard. (as of 5 March 2020)
This is a change we will be seeing very soon though, and so you should be able to cancel a request by using an AbortController
s AbortSignal
.
The way it works is this:
Step 1: You create an AbortController
(For now I just used this)
const controller = new AbortController()
Step 2: You get the AbortController
s signal like this:
const signal = controller.signal
Step 3: You pass the signal
to fetch like so:
fetch(urlToFetch, {
method: 'get',
signal: signal, // <------ This is our AbortSignal
})
Step 4: Just abort whenever you need to:
controller.abort();
Here's an example of how it would work (works on Firefox 57+):
<script>_x000D_
// Create an instance._x000D_
const controller = new AbortController()_x000D_
const signal = controller.signal_x000D_
_x000D_
/*_x000D_
// Register a listenr._x000D_
signal.addEventListener("abort", () => {_x000D_
console.log("aborted!")_x000D_
})_x000D_
*/_x000D_
_x000D_
_x000D_
function beginFetching() {_x000D_
console.log('Now fetching');_x000D_
var urlToFetch = "https://httpbin.org/delay/3";_x000D_
_x000D_
fetch(urlToFetch, {_x000D_
method: 'get',_x000D_
signal: signal,_x000D_
})_x000D_
.then(function(response) {_x000D_
console.log(`Fetch complete. (Not aborted)`);_x000D_
}).catch(function(err) {_x000D_
console.error(` Err: ${err}`);_x000D_
});_x000D_
}_x000D_
_x000D_
_x000D_
function abortFetching() {_x000D_
console.log('Now aborting');_x000D_
// Abort._x000D_
controller.abort()_x000D_
}_x000D_
_x000D_
</script>_x000D_
_x000D_
_x000D_
_x000D_
<h1>Example of fetch abort</h1>_x000D_
<hr>_x000D_
<button onclick="beginFetching();">_x000D_
Begin_x000D_
</button>_x000D_
<button onclick="abortFetching();">_x000D_
Abort_x000D_
</button>
_x000D_