Set Timeout to Fetch Action
Published
13 October 2023Tags
If you have a fetch action like the code below,
fetch("/some-endpoint-url")
.then(response => {
// ...
})
.catch(error => {
// ...
});
or by using axios like this,
axios.get("/some-endpoint-url")
.then(response => {
// ...
})
.catch(error => {
// ...
});
then, there is a case that we want to set a time out to your action call, say you want to set time out to 5 seconds, and will tell the user with some errors if the request isn’t sending back any responses within the duration.
We have an option to setup the time out by using a native JavaScript class by using AbortController
. This is the cleanest way to set a time out to your fetch action in JavaScript.
As an initiation, create an abortController
instance like this,
const abortController = new AbortController();
Then, extract it to gain an access the signal
property.
const signal = abortController.signal;
Pass this signal
to the fetch action call as a part of it options, like this,
// with fetch
fetch("/some-endpoint-url", { signal })
// with axios
axios.get("/some-endpoint-url", { signal })
And now we can set a setTimeout with interval to 5 seconds then call an abort() function from the controller to abort the fetch action or reject it with a DOMException. Put this code below outside the fetch action call.
...
setTimeout(() => {
abortController.abort();
}, 5000); // in 5 seconds
For the last touch, we can handle the error in catch block to do some logging or showing the error to the user.
.catch(error => {
if (error.name === "AbortError") {
console.error("Fetch request time out");
} else {
console.error("Fetch failed: error");
}
});
Reference: AbortController: signal property - Web APIs | MDN (mozilla.org)