Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Promise timeout wrapper in JavaScript

23 A timeout wrapper, and the loser it does not cancel

hard

Write withTimeout(work, ms, clock) that rejects if the work has not settled in time. Use an injected clock so the boundary is exact. Then show two things the race does not do: it does not fire early, and it does not stop the loser.

Stuck? Three hints, smallest first
  1. 1. Promise.race between the work and a timer that rejects when it fires.
  2. 2. The clock hands out promises that resolve only when you advance it past their deadline.
  3. 3. A race settles with the first outcome. The other promise is not cancelled, it is merely ignored.

The answer

// A clock you drive by hand: timers fire only when you advance past them.
function manualClock() {
  let now = 0;
  const timers = [];
  return {
    get time() { return now; },
    get pending() { return timers.length; },
    wait(ms) { return new Promise((resolve) => timers.push({ at: now + ms, resolve })); },
    async advance(ms) {
      now += ms;
      for (const t of timers.filter((t) => t.at <= now)) {
        timers.splice(timers.indexOf(t), 1);
        t.resolve();
      }
      for (let i = 0; i < 8; i++) await Promise.resolve();   // let the waiters run
    },
  };
}

const withTimeout = (work, ms, clock) =>
  Promise.race([
    work,
    clock.wait(ms).then(() => { throw new Error(`timed out after ${ms}ms`); }),
  ]);

const clock = manualClock();
const wonByWork = await withTimeout(Promise.resolve('paid'), 1000, clock);
const leakedTimer = clock.pending;

let finish;
const slow = new Promise((resolve) => { finish = resolve; });
const running = withTimeout(slow, 5000, clock).then((v) => 'value ' + v, (e) => e.message);
await clock.advance(5000);
const timedOut = await running;
finish('late receipt');
const workStillFinished = await slow;

const edge = manualClock();
const onTheBoundary = withTimeout(new Promise(() => {}), 100, edge).catch((e) => e.message);
await edge.advance(99);
const notYet = edge.pending;
await edge.advance(1);
const fired = await onTheBoundary;

console.log('work won  :', wonByWork, '- timers still pending:', leakedTimer);
console.log('timed out :', timedOut);
console.log('yet the work finished anyway:', workStillFinished);
console.log('at 99ms pending:', notYet, ' at 100ms:', fired);

Output


      
8 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('the work won the race', wonByWork, 'paid');
test('but the loser is not cancelled: the timer is still pending', leakedTimer, 1);
test('when the timer wins, the caller gets a rejection', timedOut, 'timed out after 5000ms');
test('yet the work carries on and completes, unaborted', workStillFinished, 'late receipt');
test('at 99ms the timer has not fired', notYet, 1);
test('at exactly 100ms it does', fired, 'timed out after 100ms');
test('and the clock reads 100, with no real time spent', edge.time, 100);
test('a timeout of 0 fires as soon as the clock moves at all', await (async () => { const c = manualClock(); const p = withTimeout(new Promise(() => {}), 0, c).catch((e) => e.message); await c.advance(0); return p; })(), 'timed out after 0ms');

A timeout is a race, and a race has no opinion about the loser. The second and fourth assertions are the two halves of that: after the work wins, the timer is still sitting in the queue; after the timer wins, the work runs to completion and its result is discarded. Neither is stopped, because a promise is a value that will arrive, not a task you can call off.

Both halves cost something real. A leaked timer keeps a callback and its closure alive — with setTimeout in Node it also keeps the process from exiting — so production code clears it in a finally. And an unaborted request keeps a socket and a database transaction open behind a caller who has already given up, which is how a slow dependency turns into an exhausted connection pool. Cancelling the underlying work needs cooperation from the work itself: an AbortSignal, or the token in exercise 33.

The boundary assertions are why the clock is injected rather than real. notYet === 1 at 99ms and fired at exactly 100ms is a statement about the comparison being <=, and with a real timer it would be a statement about how busy the machine was.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.