Sub topic 9
Building a Timeout with Promise.race
This chapter assumes you know async/await, try/catch/finally, and how setTimeout schedules a callback. It also assumes you have read the previous chapter, which covered how Promise.race settles with the first input to settle. Here that rule becomes a reusable timeout helper. You will also see the two mistakes people usually make with it: leaving the timer running, and assuming the slow operation stops.
The Idea: Race the Work Against a Clock
Promise.race does not care whether its first settled input fulfilled or rejected. If you race a real operation against a promise that rejects after ms milliseconds, one of two things happens:
- The operation settles first. Its value or its error becomes the result.
- The clock rejects first. The race rejects with a timeout error.
The clock is an ordinary promise built from setTimeout. It never fulfills. It can only reject.
A First Attempt and Its Leak
The shortest version looks correct, and the result it returns is correct:
// leaky.mjs
function withTimeoutLeaky(promise, ms) {
const timeout = new Promise((_, reject) => {
setTimeout(() => reject(new Error(`Timed out after ${ms} ms`)), ms);
});
return Promise.race([promise, timeout]);
}
const delay = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
const start = Date.now();
const value = await withTimeoutLeaky(delay(10, 'quick'), 5000);
console.log(value, `after ${Date.now() - start} ms`); // quick after ~10 ms
// The Node process does not exit for about 5 more seconds.The answer arrives after about 10 ms, but the 5-second timer is still scheduled. When the timer fires, it rejects a promise that no longer matters. That causes three practical problems:
- In Node.js, a pending timer keeps the event loop alive. CLI scripts and test runners hang until the longest timeout passes. Jest reports this as "open handles".
- The timer's closure holds references to
rejectand the error message until it fires. A server that wraps thousands of requests per second with a 30-second timeout keeps thousands of useless timers alive. - In a long-lived process the timers pile up silently. Nothing fails, so nobody notices.
The late rejection does not cause an "unhandled rejection" warning. Promise.race attaches handlers to every input, so the timeout promise counts as handled even after the race has been decided. The bug here is the timer, not the error.
The Correct Version: Clear the Timer in finally
Keep a handle to the timer and clear it however the race ends:
// timeout.mjs
export class TimeoutError extends Error {
constructor(ms) {
super(`Timed out after ${ms} ms`);
this.name = 'TimeoutError';
this.ms = ms;
}
}
export async function withTimeout(promise, ms) {
let timer;
const timeout = new Promise((_, reject) => {
timer = setTimeout(() => reject(new TimeoutError(ms)), ms);
});
try {
return await Promise.race([promise, timeout]);
} finally {
clearTimeout(timer);
}
}Each detail does a specific job:
let timeris declared outside the executor. ThePromiseexecutor runs synchronously, sotimeris assigned beforePromise.raceis called and beforefinallycan run.return awaitmatters. Writingreturn Promise.race(...)withoutawaitwould leave thetryblock at once, sofinallywould clear the timer before the race had even started. The timeout would never fire.finallycovers every exit path: the operation fulfills, the operation rejects, or the timer fires. CallingclearTimeouton a timer that has already fired does nothing, so the timeout path needs no special case.TimeoutErrorgives callers a reliable way to tell a timeout apart from the operation's own failure. Matching on the message text breaks easily.
Here is how it behaves:
// demo.mjs
import { withTimeout, TimeoutError } from './timeout.mjs';
const delay = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
const failAfter = (ms, msg) =>
new Promise((_, reject) => setTimeout(() => reject(new Error(msg)), ms));
// 1. Finishes in time
console.log(await withTimeout(delay(50, 'fast'), 200)); // fast
// 2. Too slow
try {
await withTimeout(delay(500, 'slow'), 100);
} catch (err) {
console.log(err instanceof TimeoutError, err.message); // true Timed out after 100 ms
}
// 3. Fails in time: the operation's own error comes through unchanged
try {
await withTimeout(failAfter(20, 'database refused connection'), 200);
} catch (err) {
console.log(err instanceof TimeoutError, err.message); // false database refused connection
}Callers can then handle the two kinds of failure differently:
// retry-on-timeout.mjs
import { withTimeout, TimeoutError } from './timeout.mjs';
export async function loadWithOneRetry(load, ms) {
try {
return await withTimeout(load(), ms);
} catch (err) {
if (err instanceof TimeoutError) {
return withTimeout(load(), ms * 2); // slow, so try once more with more time
}
throw err; // real failure: do not retry
}
}The helper receives a load function, not a promise. A retry has to start a new operation. Re-awaiting the same promise would only return the same outcome again.
The Timeout Does Not Stop the Operation
In case 2 above, withTimeout rejected after 100 ms, but delay(500, 'slow') kept running and fulfilled at 500 ms with nobody listening. A promise represents a result. It has no handle on the work that produces the result, and Promise.race cannot reach that work to stop it.
When an abandoned operation rejects later, its rejection is absorbed silently, because Promise.race attached a handler to it. That avoids crashes, but it also means late errors are invisible. If you need to log them, attach your own .catch to the original promise before passing it in.
Variant: Fall Back Instead of Failing
Sometimes a slow answer is worse than a default answer, for example a recommendations widget that should show "popular items" when the personalised service is slow. In that case the clock resolves instead of rejecting:
// fallback.mjs
export async function withFallback(promise, ms, fallbackValue) {
let timer;
const fallback = new Promise((resolve) => {
timer = setTimeout(() => resolve(fallbackValue), ms);
});
try {
return await Promise.race([promise, fallback]);
} finally {
clearTimeout(timer);
}
}
const slowRecs = new Promise((resolve) => setTimeout(() => resolve(['for you']), 300));
console.log(await withFallback(slowRecs, 100, ['popular'])); // ['popular']If the real operation rejects before the deadline, that rejection still wins the race. To fall back on errors too, add .catch(() => fallbackValue) to the input promise.
Edge Cases and Gotchas
| Situation | What happens | What to do |
|---|---|---|
| `ms` is `0` or negative | The timer fires on the next timer tick. An already-resolved input still wins, because its reaction job runs before any timer callback. | Validate `ms` if it comes from configuration. |
| `ms` is `undefined` or `NaN` | `setTimeout` treats it as 0, so the call almost always times out. | Throw a `TypeError` on non-finite values. |
| `ms` is above 2,147,483,647 | Node and browsers overflow the 32-bit delay and fire almost at once. | Clamp the value, or treat very large values as "no timeout". |
| Input is a plain value, not a promise | `Promise.race` wraps it as already fulfilled, so it wins. | No action needed. |
| Building the input throws synchronously | The throw happens before `withTimeout` is called. | Wrap the call in `try`, or make the producer an `async` function. |
| Same timeout covering several steps | Wrap the whole chain: `withTimeout(stepA().then(stepB), ms)`. | Wrapping each step separately gives each step the full budget. |
Modern runtimes also provide AbortSignal.timeout(ms), which creates a signal that aborts on its own after ms. APIs that accept a signal, such as fetch, both stop waiting and cancel the work when it fires. Prefer it where the API supports signals. Use the Promise.race helper for promises that have no cancellation hook.
Exercise
Someone shortens withTimeout to try { return Promise.race([promise, timeout]); } finally { clearTimeout(timer); }. Then await withTimeout(delay(500, 'slow'), 100) returns 'slow' after 500 ms instead of throwing. Why?
Show answer
Without await, the return hands the race promise back right away, so finally runs before the race settles and clears the timer. The timeout promise then never rejects, and the race waits for the operation alone. Writing return await keeps the try block open until the race settles.
Exercise
Using the correct withTimeout, a script runs await withTimeout(delay(3000, 'x'), 100) inside try/catch and logs the error. Roughly when is the error logged, and roughly when does the Node process exit?
Show answer
The TimeoutError is logged after about 100 ms. The process exits after about 3000 ms, because the 3-second timer inside delay is still pending. clearTimeout only cleared the timeout's own timer, and the race cannot cancel the underlying operation.
Exercise
Write withDeadline(promises, ms), which waits for all of an array of promises but rejects with TimeoutError if they have not all fulfilled within ms. Reuse withTimeout.
Show answer
const withDeadline = (promises, ms) => withTimeout(Promise.all(promises), ms); This gives one shared deadline for the whole group, because Promise.all produces a single promise and withTimeout races that one promise against one timer.