DEV Community


Posted on • Updated on


Axios is an external library used in making promised based HTTP requests. One of the coolest things that comes with it people hardly talk about is the axios timeout functionality.

This article simply explains how to use the axios timeout functionality to optimize/minimize the time it takes to make HTTP requests.

So when you make HTTP requests to a web server there would be sometimes when a response would be delayed for no reason. You may want to avoid this unnecessary delay with axios timeout object. What the axios timeout does is that it would abort a request when it takes longer time. Since the time is measured in milliseconds, whatever seconds set to it is how long the request takes and once it exceeds that times, the request is aborted. The default time is set to 0 which indicates no timeout. This gives you some form of control over making requests.

Here is how you can globally set timeout with axios.

import axios from axios;
axios.defaults.timeout === 3000;

One important thing to note is that axios timeout is response/request bound and not connection bound. What this means is that if there is no network on the clients side or for some reason the IP address is not found or may be the domain name is not found, axios timeout isn't going to work. But if for instance the server your making a request to is taking too long to load, then axios time out will work.

You can also set axios timeout this way

import axios from axios ;

.post(‘url’, {timeout: 3000})
.then((res) => console.log(res))
.catch((err) => console.log(err))
Enter fullscreen mode Exit fullscreen mode

In this case if your response takes more than 3 seconds, it goes into the catch block.

Discussion (0)