Have you ever faced an issue that your webpage fails to finish a request due to backend crashing or it's too long to respond, and the app just waits for it - which seems to take forever.
In JavaScript, from ES6 and later*, there is a built-in method that we can use to implement the timeout feature very easily, called
Promise.race. Let me show you how.* JavaScript's
Promise.race method is introduced in ECMAScript 2015 (ES6). This means any JavaScript engine that supports ES6 or later versions will have built-in support for Promise.race. What is Promise.race?What is Promise.race?
What is Promise.race?What is Promise.race?
Promise.race is a method provided by the Promise object in JavaScript. It takes an iterable of promises (like an array) as input and returns a new promise. This new promise settles (either resolves or rejects) as soon as one of the promises in the iterable settles.Use Promise.race to implement timeout functionalityUse Promise.race to implement timeout functionality
Use Promise.race to implement timeout functionalityUse Promise.race to implement timeout functionality
First, create a function with the following code - name it
timeout.javascript
export const timeout = function (sec) { return new Promise(function (_, reject) { setTimeout(function () { reject(new Error('Request took too long!')); }, sec * 1000); }); };
The timeout function
This function should be put inside a file where you leave all the reusable functions, such as utils, helpers...
Second, in your async request, put your request call or any promise, async/await function and
timeout function call inside an array in Promise.race, as follow:javascript
const res = await Promise.race([ axios.post(ENDPOINT_URL, requestBody), timeout(20) ]);
In this example, the request will timeout after 20s
In this situation,
Promise.race will return immediately after either the axios.post finishes its operation or the timeout occurs. This way, you can proactively control the timeout period for your request, ensuring it won't take too long to respond.Client-side timeouts with JavaScript offer a way to control the responsiveness of your application by preventing requests from taking too long. This approach is independent of the server-side configuration for the original request. However, it's important to consider that the server might still be processing the request even after the client times out**.
** In this case, you may need other way to tackle this issue, such as server-side timeouts, or cancellation tokens - such as AbortController. See below for more examples with Axios.
Better ways with Axios/FetchBetter ways with Axios/Fetch
Better ways with Axios/FetchBetter ways with Axios/Fetch
From Node.js 17.3+, you can use directly
AbortSignal.timeout(millisecond) as a signal in the axios request. Like so:javascript
axios.get('/foo/bar', { signal: AbortSignal.timeout(5000) //Aborts request after 5 seconds }).then(function(response) { //... });
Example of using AbortSignal.timeout with Axios. Source: Axios document.
Or a helper function with a setTimeout inside as a signal.
javascript
function newAbortSignal(timeoutMs) { const abortController = new AbortController(); setTimeout(() => abortController.abort(), timeoutMs || 0); return abortController.signal; } axios.get('/foo/bar', { signal: newAbortSignal(5000) //Aborts request after 5 seconds }).then(function(response) { //... });
Example of using helper function as a signal in Axios. Source: Axios document.
Of course, these two approaches can work well with traditional
fetch request, not just axios. Hope this helps! Thanks for reading and let me know if you have any discussions.

