If you're making an API call in JavaScript and want to set a timeout of 5 seconds after which the API call should be stopped to prevent an error, you can use the setTimeout()
function.
Here's an example of how to set a timeout for an API call using the fetch()
function in JavaScript:
javascriptconst timeout = 5000; // 5 seconds in milliseconds
const url = 'https://example.com/api';
// Call the API with a timeout of 5 seconds
const apiCall = fetch(url, { method: 'GET' });
const timeoutPromise = new Promise((_, reject) => {
setTimeout(() => {
reject(new Error('Request timed out'));
}, timeout);
});
Promise.race([apiCall, timeoutPromise])
.then((response) => {
// Handle successful response from the API
})
.catch((error) => {
// Handle timeout or API error
});
In this example, we create a timeoutPromise
that will reject after 5 seconds using the setTimeout()
function. We then use Promise.race()
to race the API call and the timeout promise, so whichever one resolves or rejects first will be used.
If the API call is successful and returns a response before the timeout, the .then()
callback will be executed. Otherwise, if the timeout occurs before the API call is completed, the .catch()
callback will be executed with an error message indicating that the request timed out.