Learn how to timeout a fetch request
In this article, you will learn about how to timeout a fetch request.
A fetch timeout is a useful approach to tell the user about the network problem or any other occurrence after making them wait for a few moments. There can be many reasons for failing an HTTP request such as server issues, DNS issues or the user may make himself offline. Let’s see how we can set a timeout on a request by using setTimeout() and the abort controller.
If you don’t set a timeout, the browser will do it for you, and by default, the time is indicated by the browser. It can be varied and the time depends on the browser, for example, firefox has 90seconds on the other hand chrome has 300seconds
async function loadData() {
const response = await fetch('/data');
const data = await response.json();
return data;
}
Here, the data will be loaded within 300 seconds in chrome browser and 90 seconds in firefox. Let’s see an example of timeout a fetch request and setting the time limit manually.
async function fetchWithTimeout(resource, options = {}) {
const { timeout = 5000 } = options;
const abortController = new AbortController();
const id = setTimeout(() => abortController.abort(), timeout);
const response = await fetch(resource, {
...options,
signal: abortController.signal
});
clearTimeout(id);
return response;
}
Here, we set the functionality so that we can set the time manually. Fetch request alone can not do this and this is the reason we are using abortController. Now we can use it on our own function. See the below code example
async function loadData() {
try {
const response = await fetchWithTimeout('/games', {
timeout: 5000
});
const data = await response.json();
return data;
} catch (error) {
console.log(error);
}
}
This function will wait for 5 seconds to load data and if there’s any error occurred then it will be shown after the 6 seconds. This is how you can use a fetch timeout.