When making a fetch request in JavaScript, there might be a scenario where you would want to cancel the request if it's taking too long. This can be useful if you want to prevent your application from hanging indefinitely due to either a network issue, or a slow response.
In this post I will cover how you can use the AbortController to exit a fetch request after a specified amount of time.
Using 'AbortController'
The AbortController interface provides a method named 'abort' that can be used to cancel web requests that are initiated by the fetch API. The interface also provides a signal property, which is passed to the fetch request.
The signal will then listen for potential abort events and cancel the requests as needed.
By combining the AbortController with the setTimeout method, we can specify just when we would like the fetch to exit.
function fetchWithTimeout(url, timeout) {
return new Promise((resolve, reject) => {
const controller = new AbortController();
const signal = controller.signal;
// Set a timeout to abort the fetch request
const timeoutId = setTimeout(() => {
controller.abort();
}, timeout);
fetch(url, { signal })
.then(response => {
clearTimeout(timeoutId); // Clear the timeout if request is successful
resolve(response);
})
.catch(error => {
if (error.name === 'AbortError') {
reject(new Error('Request timed out'));
} else {
reject(error);
}
});
});
}
And in your code, you can call the function as follows:
const url = 'https://api.example.com/data';
const timeout = 5000; // 5 seconds
fetchWithTimeout(url, timeout)
.then(response => response.json())
.then(data => {
console.log('Data received:', data);
})
.catch(error => {
console.error('Fetch error:', error);
});
Ideally of course, if you are having performance issues with your fetch requests, the better solution would be to try and improve the overall speed of the request, and not simply just cancel it.
But as a potential secondary backup strategy, having timeouts in place can definitely improve the overall user experience in case such a thing is ever needed.
And lastly, the AbortController isn't just intended to be used with fetch requests. It can also be used to end other asynchronous operations. For example, you can use the AbortController interface to clear a timeout or interval if they are no longer required.
const controller = new AbortController();
const signal = controller.signal;
const intervalId = setInterval(() => {
console.log('Interval running');
}, 1000);
signal.addEventListener('abort', () => {
clearInterval(intervalId);
});
setTimeout(() => {
controller.abort();
}, 5000); // Clear the interval after 5 seconds
AbortController is a great tool to use for managing the life cycle of asynchronous operations in your web applications.
Walter Guevara is a Computer Scientist, software engineer, startup founder and previous mentor for a coding bootcamp. He has been creating software for the past 20 years.
Last updated on:
Have a question on this article?
You can leave me a question on this particular article (or any other really).
Ask a question