Skip to curriculum
Jump to the editor

11.7. Chain calls with optional delays

Medium
Topics

This question is in

11. Timers
20–35 min

An onboarding tour shows a tip, waits two seconds, highlights a button, waits again, then opens a panel. A test script types, waits, clicks, waits for a request. Written with nested setTimeout calls, each step sits one level deeper than the last. A chain reads the way the steps happen: tour.do(showTip).wait(2000).do(highlight).wait(1000).do(openPanel), and runs them one after another by itself.

Write chain() in chain.js. It returns an object whose methods queue steps and return the same object, so calls can be chained. The queue starts running on its own once the code that built it has finished.

Signature

JAVASCRIPT
function chain() // returns { do, wait, waitFirst, done }
  • do(fn, ...args): queue a call of fn(...args). If it returns a promise, the chain waits for it before the next step. Returns the chain.
  • wait(ms): queue a pause of ms milliseconds. Returns the chain.
  • waitFirst(ms): put a pause of ms in front of every step that has not started yet. Returns the chain.
  • done(): returns a promise that resolves, once the queue is empty, with an array of the values every do step has produced so far (in order), or rejects with the first error.

Requirements

  1. do, wait and waitFirst return the chain itself. The chain is not a thenable: it has no then method.
  2. No step runs while the chain is being built. The chain starts by itself in a microtask once the current code has finished, so a chain with no waits has run before any timer fires.
  3. Steps run one at a time, in the order they were queued. fn receives the extra arguments given to do.
  4. wait(ms) delays everything after it by ms; waits add up. wait(0) still goes through a 0 ms timer.
  5. waitFirst(ms) adds a pause before every step that has not started yet, even if it is called last. A step that is already running (a pause, or an async fn) finishes first.
  6. When fn returns a promise, the next step starts only after it settles; its resolved value is the step's result.
  7. Steps queued while the chain is running, including from inside a step, run after the steps already queued. Steps queued after the chain has finished start it again.
  8. done() resolves with the results of every do step so far, as a new array, once nothing is left to run. On a chain that has nothing to do, it resolves with [] straight away.
  9. If fn throws or its promise rejects, the chain stops: the remaining steps never run, and done() rejects with that error, now and on every later call. Steps queued after a failure are ignored.
  10. Each chain is independent of the others.

Examples

JAVASCRIPT
chain()
  .do(console.log, "a")   // 0 ms:   a
  .wait(100)
  .do(console.log, "b")   // 100 ms: b
  .wait(200)
  .do(console.log, "c");  // 300 ms: c
JAVASCRIPT
chain()
  .do(console.log, "a")
  .wait(100)
  .do(console.log, "b")
  .waitFirst(50);
// 50 ms: a, 150 ms: b: the pause went in front of everything
JAVASCRIPT
const results = await chain()
  .do(() => 1)
  .do(() => new Promise((resolve) => setTimeout(resolve, 100, 2)))
  .do((x) => x * 10, 3)
  .done();
// results: [1, 2, 30], 100 ms after the start
JAVASCRIPT
await chain().do(() => { throw new Error("broken"); }).do(console.log, "never").done();
// rejects with Error("broken"); "never" is not printed

Environment

  • Plain JavaScript in a browser page; the tests call the global chain from chain.js.
  • The tests run on a virtual clock that replaces setTimeout, clearTimeout and Date.now; use setTimeout for the waits. Promises and queueMicrotask are the real ones.
  • Canceling a chain, and timeouts for slow steps, are not part of this problem.

Hints

  1. With every step in one array, which array methods add to the back, add to the front, and take the next step?
  2. If the steps run inside one async function, how can a pause become something that function can await?
  3. Why must the chain object not have a method called then?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…