Course contentsShow
← JavaScript
Lesson 2305 of 2,72347. Networking PrimitivesFree lesson

AbortSignal.timeout for Automatic Cancellation

Use the static AbortSignal.timeout method to create signals that auto-abort after a delay.

AbortSignal.timeout for Automatic Cancellation

You'll learn how to create abort signals that automatically cancel operations after a time limit—no manual controller needed.

The Static Shortcut for Time-Based Cancellation

You already know how to create an AbortController, wire up its signal, and manually call abort(). But what if you just want a request to timeout after, say, 5 seconds? That's exactly what AbortSignal.timeout() is for.

This static method creates an abort signal that automatically aborts after a specified number of milliseconds. No controller to manage, no manual abort call—just set it and forget it.

How It Works

Instead of creating a controller, you call AbortSignal.timeout(ms) directly and pass the resulting signal to your fetch:

// Automatically abort after 3 seconds
const response = await fetch('https://api.example.com/data', {
  signal: AbortSignal.timeout(3000)
});

If the request takes longer than 3 seconds, it aborts automatically. You still handle the AbortError the same way:

try {
  const response = await fetch('https://slow-api.com/data', {
    signal: AbortSignal.timeout(2000)
  });
  const data = await response.json();
} catch (err) {
  if (err.name === 'AbortError') {
    console.log('Request timed out after 2 seconds');
  }
}

When to Use It

Use AbortSignal.timeout() when you have a fixed time limit and don't need to cancel manually. It's cleaner than setting up a timer with AbortController yourself.

Key Takeaway: AbortSignal.timeout(ms) creates a self-aborting signal that cancels operations automatically after the specified delay, perfect for simple timeout scenarios.