Request Timeouts with AbortSignal.timeout()
You'll learn how to automatically cancel slow requests using a built-in timeout mechanism.
In the previous lesson, you learned to abort requests manually with AbortController. Now there's an even simpler way to handle a common scenario: timing out requests that take too long.
Why Timeouts Matter
Imagine ordering food delivery with a strict "must arrive in 30 minutes or it's free" policy. You don't want to wait indefinitely—you need a cutoff point. Network requests are similar: sometimes a server is slow or unresponsive, and you need to give up gracefully rather than leaving users staring at a loading spinner forever.
The AbortSignal.timeout() Method
Instead of manually creating an AbortController and setting up setTimeout, you can use AbortSignal.timeout(milliseconds) to create a signal that automatically aborts after a specified time:
// Automatically abort after 5 seconds
const signal = AbortSignal.timeout(5000);
fetch('https://api.example.com/slow-endpoint', { signal })
.then(response => response.json())
.then(data => console.log('Success:', data))
.catch(error => {
if (error.name === 'AbortError') {
console.log('Request timed out after 5 seconds');
// Show user-friendly message
} else {
console.log('Other error:', error.message);
}
});
Graceful Timeout Handling
When the timeout expires, the fetch throws an AbortError, just like manual abortion. Always check error.name === 'AbortError' to distinguish timeouts from genuine network failures, so you can show appropriate messages to users.
Key Takeaway: AbortSignal.timeout() provides a clean, one-line way to enforce request time limits without manual setTimeout management—perfect for preventing hanging requests and improving user experience.