In 2025, ensuring efficient data fetching in your applications is crucial. Using Axios, a popular promise-based HTTP client for JavaScript, you can easily set a timeout for your requests to handle delays and enhance your application’s performance. Here, we’ll guide you through setting a timeout with Axios.
Setting a timeout is vital to avoid waiting indefinitely for a response. It ensures your application remains responsive and can effectively handle errors, enhancing user experience.
Follow these simple steps to set a timeout in an Axios request:
1
|
npm install axios |
or
1
|
yarn add axios |
Global Timeout:
1 2 3 |
import axios from 'axios'; axios.defaults.timeout = 5000; // Set timeout to 5 seconds |
Per-Request Timeout:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import axios from 'axios'; axios.get('https://example.com/data', { timeout: 5000 // Timeout set to 5 seconds }) .then(response => { console.log(response.data); }) .catch(error => { if (error.code === 'ECONNABORTED'){ console.error('Request timed out'); } else { console.error('Request failed', error); } }); |
error.code
to handle it efficiently.Setting a timeout in Axios requests is a simple yet effective way to manage your application’s network interactions. By following the steps above, you can ensure smoother user experiences in 2025 and beyond. “`
This article provides a succinct guide on setting a timeout in Axios requests and includes relevant links to enhance understanding of related JavaScript concepts.