How can I set a timeout for AJAX requests in Javascript without jquery? Is it done by setting up a timer and using cancelRequest? or a better way? Many thanks
Yes, you can set a timeout for AJAX requests in JavaScript without jQuery by using the AbortController API.
function fetchWithTimeout(url, timeout = 5000) {
const controller = new AbortController();
const signal = controller.signal;
// Set up a timeout to abort the fetch request
const timeoutId = setTimeout(() => controller.abort(), timeout);
return fetch(url, { signal })
.then(response => {
clearTimeout(timeoutId); // Clear the timeout if request succeeds
return response.json();
})
.catch(error => {
if (error.name === 'AbortError') {
console.error('Request timed out');
} else {
console.error('Fetch error:', error);
}
throw error; // Rethrow the error for handling
});
}
// Usage
fetchWithTimeout('https://jsonplaceholder.typicode.com/todos/1', 3000)
.then(data => console.log('Data:', data))
.catch(error => console.log('Error:', error));