Race a task against a timeout and abort it on expiry
A checkout page calls a pricing service, a tax service and a fraud check. If any of them hangs, the page must give up after a few seconds and show a fallback, instead of spinning forever. Giving up is not enough on its own, though: the slow request should also be told to stop, so it does not keep the connection busy.
Implement withDeadline(task, ms). It returns a promise that settles like task if the task finishes within ms milliseconds, and rejects with a timeout error otherwise.
withDeadline(task, ms) // => Promise
task can be a promise (or any thenable), a plain value (treated like Promise.resolve(value)), or a function.withDeadline, with an AbortSignal as its only argument: task(signal). Its return value (a promise or a plain value) is the work to wait for. It can pass the signal to fetch so the request is cancelled on timeout.clearTimeout.ms passes first, reject with an Error whose name is 'TimeoutError' and whose message is `Timed out after ${ms}ms`. If the task is a function, also abort its signal, with that same error as signal.reason.setTimeout for the deadline. A ms that is negative or not a number is treated as 0 (and the message says 0ms).ms = Infinity means “no deadline”: do not start a timer, just settle like the task.await withDeadline(fetchPrice(), 2000); // => the price, if it arrives within 2s
const slow = new Promise((resolve) => setTimeout(() => resolve('late'), 5000));
await withDeadline(slow, 100);
// rejects: Error { name: 'TimeoutError', message: 'Timed out after 100ms' }
await withDeadline((signal) => fetch('/api/tax', { signal }), 3000);
// on timeout, the fetch is aborted with the TimeoutError as its reason
await withDeadline(42, 10); // => 42
await withDeadline(Promise.reject(new Error('boom')), 10); // rejects with that 'boom' error
The tests replace setTimeout and clearTimeout with a fake clock, so call the global functions when withDeadline runs and do not rely on Date.now().