Sometimes, we want to fix timeout feature in the axios library is not working with JavaScript.
In this article, we’ll look at how to fix timeout feature in the axios library is not working with JavaScript.
How to fix timeout feature in the axios library is not working with JavaScript?
To fix timeout feature in the axios library is not working with JavaScript, we use a cancel token.
For instance, we write
const source = CancelToken.source();
const timeout = setTimeout(() => {
source.cancel();
}, 10000);
const result = await axios.get(ip + "/config", { cancelToken: source.token });
clearTimeout(timeout);
to call axios.get
with the cancelToken
we created with CancelToken.source
.
Then we source.cancel
in the setTimeout
callback to cancel the get request when the request hasn’t finished in 10 seconds.
If the request is done before then, we use clearTimeout(timeout);
to clear the timer.
Conclusion
To fix timeout feature in the axios library is not working with JavaScript, we use a cancel token.