Sub topic 13
Adding Deadlines with AbortSignal.timeout()
This chapter assumes you already have the cancellable delay() from earlier chapters, and that you know how to tell an AbortError apart from other errors in a catch block. Here you will add a deadline. A deadline is a cancellation source that fires on its own once a set time has passed, with no user action needed.
What AbortSignal.timeout() Gives You
AbortSignal.timeout(ms) is a static method that returns a new signal. That signal aborts itself after ms milliseconds. It has no controller, so you cannot abort it early or reset it. When it fires, signal.reason is a DOMException named "TimeoutError", not "AbortError".
That difference in name is the useful part. A caller can tell "the user gave up" apart from "the operation ran out of time" without any extra bookkeeping.
| Source | How it aborts | `signal.reason.name` |
|---|---|---|
| `controller.abort()` | Your code calls it | `"AbortError"` |
| `AbortSignal.timeout(ms)` | Timer expires | `"TimeoutError"` |
| `controller.abort(customErr)` | Your code calls it | Whatever `customErr` is |
Your Functions Already Support It
delay() rejects with signal.reason, so it handles a timeout signal with no changes. Any function that follows the conventions from earlier chapters works the same way.
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(5000, { signal: AbortSignal.timeout(1000) });
console.log('finished');
} catch (err) {
if (err.name === 'TimeoutError') {
console.log('gave up after 1 second');
} else {
throw err;
}
}
}
main();The same thing works with fetch. If the deadline passes, the request is aborted and fetch rejects with the TimeoutError:
async function loadUser(id) {
const response = await fetch(`/api/users/${id}`, {
signal: AbortSignal.timeout(3000),
});
return response.json();
}Common Mistakes
Creating the signal too early
The countdown starts when you call AbortSignal.timeout(), not when the work starts. If you store one timeout signal in a module-level constant and reuse it, every call after the deadline fails at once, because the signal is already aborted. Create a fresh timeout signal for each operation.
Expecting to cancel the deadline
You cannot clear a timeout signal. If you need a deadline and also a manual cancel button, you need two signals combined. The next chapter covers that with AbortSignal.any().
Assuming wall-clock time
In browsers, the timer counts active time only. It pauses while the document is inactive, for example when a page sits in the back/forward cache. Don't rely on it for exact wall-clock scheduling.
Exercise
A module defines const DEADLINE = AbortSignal.timeout(2000); and passes DEADLINE to every fetch call. Calls in the first two seconds after the page loads work, but every later call fails right away. Why, and how do you fix it?
Show answer
The countdown starts when the module runs, so after two seconds the shared signal is permanently aborted. Every later fetch sees an already-aborted signal and rejects with a TimeoutError straight away. The fix is to call AbortSignal.timeout(2000) inside each request, so every operation gets its own fresh deadline.
Exercise
Your catch block checks only err.name === 'AbortError'. What happens when a timeout signal fires?
Show answer
The timeout's reason is named "TimeoutError", so the check fails. If the block rethrows unrecognized errors, the timeout escapes as an unhandled failure. Add a separate branch for "TimeoutError".