Sub topic 13
Adding Deadlines with AbortSignal.timeout()
Earlier chapters cancelled work when a person or a piece of code called controller.abort(). Plenty of work also needs to stop when time runs out, even if nobody asks. A request that hangs for two minutes is usually worse than one that fails after five seconds. This chapter shows how to add deadlines with AbortSignal.timeout(), how it differs from a hand-built timer, and which edge cases can catch you out.
This chapter assumes you know Promises and async/await, try/catch, and fetch. It also assumes you have read the earlier chapters on signal.reason, the cancellable delay(), and checking err.name in callers.
What AbortSignal.timeout() Gives You
AbortSignal.timeout(ms) is a static method that returns a new AbortSignal. That signal aborts on its own after ms milliseconds. You don't create a controller, and you don't call abort(). When the time is up, the signal does three things:
signal.abortedbecomestrue.signal.reasonbecomes aDOMExceptionwhosenameis"TimeoutError".- The
abortevent fires.
Any function that already accepts a signal therefore supports deadlines with no extra code. The cancellable delay() from earlier works with a timeout signal as it is:
function delay(ms, { signal } = {}) {
return new Promise((resolve, reject) => {
if (signal?.aborted) {
reject(signal.reason);
return;
}
const onAbort = () => {
clearTimeout(timerId);
reject(signal.reason);
};
const timerId = setTimeout(() => {
signal?.removeEventListener('abort', onAbort);
resolve();
}, ms);
signal?.addEventListener('abort', onAbort, { once: true });
});
}
async function main() {
try {
await delay(2000, { signal: AbortSignal.timeout(500) });
console.log('finished');
} catch (err) {
console.log(err.name); // "TimeoutError"
console.log(err instanceof DOMException); // true
}
}
main();delay() has no idea a timeout exists. It rejects with signal.reason, as it always does, and the reason is now a TimeoutError. This is the benefit of the design rule from earlier chapters: reject with signal.reason and never invent your own abort error. A function that follows the rule passes along whatever the cancellation source meant.
Offering a Timeout Option in Your Own Function
You can let callers pass a timeout signal themselves, or your function can create one from a simple number option. A timeoutMs option is friendlier when a deadline is the usual case:
async function fetchJson(url, { timeoutMs = 5000 } = {}) {
const signal = AbortSignal.timeout(timeoutMs);
try {
const response = await fetch(url, { signal });
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
return await response.json();
} catch (err) {
if (err.name === 'TimeoutError') {
throw new Error(`Timed out after ${timeoutMs} ms: ${url}`, { cause: err });
}
throw err;
}
}Note the details:
- The signal is created inside the function, so every call gets its own fresh deadline.
- The deadline covers the whole response, body included. A
fetchsignal stays attached to the response body, so if headers arrive quickly but the body streams slowly,response.json()rejects with theTimeoutError. That is whyawait response.json()sits inside thetry. - The wrapped error keeps the original in
cause, and its message names the limit and the URL. Callers that checkerr.cause?.name === 'TimeoutError'can still tell it apart.
This version drops any signal option, so callers can't cancel it themselves. Supporting both a caller's signal and a timeout requires merging two signals, which the next chapter covers with AbortSignal.any().
Gotchas
The clock starts when you create the signal
A timeout signal starts counting the moment AbortSignal.timeout() runs, not when work begins. This bug looks harmless:
// Wrong: one shared signal created when the module loads
const TEN_SECONDS = AbortSignal.timeout(10_000);
export function loadUser(id) {
return fetch(`/api/users/${id}`, { signal: TEN_SECONDS });
}Ten seconds after the module loads, the signal aborts for good. Every later call to loadUser() fails right away with TimeoutError, because fetch sees an already-aborted signal. Create the timeout signal per operation, right before you start the work.
You cannot cancel or extend it
A timeout signal has no controller. You can't clear its timer, reset it, or abort it early. If the operation succeeds after 200 ms, the signal simply aborts later with nothing listening. That costs little. The real limit is that you can't build an "idle timeout" that restarts whenever data arrives. For that you need the manual approach shown below.
In Node.js, it does not keep the process alive
Node.js "unrefs" the internal timer of AbortSignal.timeout(), meaning the timer alone won't keep the event loop running. If nothing else is pending, the process exits before the signal fires:
const signal = AbortSignal.timeout(1000);
signal.addEventListener('abort', () => {
console.log('timed out'); // Never printed in Node.js
});Normally this doesn't matter, because the work you are timing (a socket, a setTimeout inside delay()) keeps the process alive. It only shows up in small experiments and in tests that wait on nothing but the signal.
It measures active time in browsers
The specification bases the timeout on active time, not wall-clock time. If a page sits in the back/forward cache, or a worker is suspended, the countdown pauses. A 5-second timeout can take much longer in real time. For a network deadline this is usually what you want. Don't use it as a precise clock.
The Manual Alternative
Before AbortSignal.timeout() existed, people combined a controller with setTimeout. That pattern still has uses:
function createDeadline(ms) {
const controller = new AbortController();
const timerId = setTimeout(() => {
controller.abort(
new DOMException(`Deadline of ${ms} ms exceeded`, 'TimeoutError')
);
}, ms);
return {
signal: controller.signal,
clear: () => clearTimeout(timerId),
abort: (reason) => {
clearTimeout(timerId);
controller.abort(reason);
},
};
}
async function main() {
const deadline = createDeadline(3000);
try {
await delay(1000, { signal: deadline.signal });
console.log('done in time');
} finally {
deadline.clear(); // stop the timer once the work is over
}
}
main();Passing a DOMException named "TimeoutError" as the reason keeps the error shape the same as the built-in, so callers that check err.name work with either version.
| Need | `AbortSignal.timeout()` | Controller + `setTimeout` |
|---|---|---|
| Simple fixed deadline | Best choice, one line | Works, more code |
| Clear the timer after success | Not possible (and rarely needed) | `clearTimeout` |
| Reset or extend the deadline | Not possible | Clear and schedule a new timer |
| Abort early by hand too | Needs `AbortSignal.any()` | Same controller |
| Keeps Node.js process alive | No | Yes, unless you call `timerId.unref()` |
| Controlled by fake timers | Not reliably | Yes |
Overall Deadline or Per-Attempt Timeout
Where you create the timeout signal decides what it limits. Look at a retry loop:
async function fetchWithRetry(url, { attempts = 3, totalMs = 8000 } = {}) {
const signal = AbortSignal.timeout(totalMs); // one deadline for everything
for (let i = 1; i <= attempts; i += 1) {
try {
const response = await fetch(url, { signal });
if (response.ok) return await response.json();
if (i === attempts) throw new Error(`Request failed: ${response.status}`);
} catch (err) {
if (err.name === 'TimeoutError' || i === attempts) throw err;
}
await delay(500 * i, { signal }); // the backoff also respects the deadline
}
}A single signal, created before the loop, gives an overall deadline. All attempts plus the waits between them must finish within totalMs. The TimeoutError check stops the loop from retrying after the deadline passes, since every retry would fail at once anyway. If you instead created AbortSignal.timeout() inside the loop, each attempt would get its own budget, and the total time could grow to attempts × timeout plus backoff. Real clients often want both limits, which again means combining signals.
Support
AbortSignal.timeout() is available in current Chrome, Edge, Firefox, and Safari (Safari 16 and later), in Node.js 16.14 / 17.3 and later, and in Deno and Bun. If you must support older runtimes, use the createDeadline() pattern above.
Exercise
A module exports const signal = AbortSignal.timeout(5000) and every API helper passes it to fetch. Requests work for a while after page load, then all of them fail immediately with TimeoutError. Explain why and fix it.
Show answer
The timeout signal started counting when the module loaded and aborted permanently 5 seconds later. From then on every fetch received an already-aborted signal and rejected at once. Create the signal per request inside each helper, for example fetch(url, { signal: AbortSignal.timeout(5000) }), so each operation gets a fresh deadline.
Exercise
In Node.js, this script exits without printing anything: AbortSignal.timeout(1000).addEventListener('abort', () => console.log('timeout')). Why, and how would you make it print?
Show answer
Node.js unrefs the timer behind AbortSignal.timeout(), so it doesn't keep the event loop alive. With nothing else pending, the process exits before the signal fires. Keep the process alive with real pending work, for example await delay(2000, { signal }) using the cancellable delay, or use the manual controller-plus-setTimeout pattern, whose timer is ref'd by default.
Exercise
You need a streaming download to fail if no data arrives for 3 seconds, while the full download may take minutes. Can AbortSignal.timeout() do this alone? Sketch the approach.
Show answer
No. A timeout signal can't be reset, and this is an idle timeout that must restart whenever a chunk arrives. Use an AbortController with a setTimeout that calls controller.abort(new DOMException('Idle timeout', 'TimeoutError')). Each time a chunk is read, call clearTimeout and schedule a new 3-second timer, then clear it when the stream finishes.