Screens

Lesson/lessons/:id

No translation yet
Showing the original.

setTimeout(fn, 100) does not promise that fn runs after 100 ms. It promises that fn will not run sooner.

Node.js keeps timers in a min-heap ordered by expiry time. At the start of each loop iteration, the timers phase runs every whose time has passed. Then the loop moves on to pending callbacks, poll, check and close. A timer that expires while the loop is busy elsewhere waits for the next pass.

Two consequences follow:

  • A long synchronous task delays every timer behind it.
  • Between two tasks, Node.js drains process.nextTick callbacks and then promise jobs. A timer never cuts in front of them.
jstimers.cjs
const start = performance.now();
const since = () => Math.round(performance.now() - start) + " ms";

setTimeout(() => console.log("timer", since()), 10);
setImmediate(() => console.log("immediate", since()));
Promise.resolve().then(() => console.log("promise job", since()));
process.nextTick(() => console.log("nextTick", since()));

// Block the loop for 50 ms.
while (performance.now() - start < 50);
console.log("sync done", since());

The output is sync done, nextTick, promise job, timer, immediate, all at about 50 ms. The timer asked for 10 ms and got 50.

js
Bad
Removed: report(intervalMs);
Good
Added: report(performance.now() - start);

Measure how long the timer actually waited.

When a timer can run
Once the delay has elapsed, the callback still waits for the event loop to reach it.
The Node.js event loopnodejs.org

The official guide. Read the phases overview, then the section that compares setImmediate() with setTimeout().

Philip Roberts, JSConf EU. 26 minutes. It shows the browser, but the queue model carries over.

A timer expires during a synchronous loop. Why does its callback not interrupt the loop?
  1. The timer resets whenever the loop iterates.
  2. The callback passed to setTimeout waits for the loop to return.
  3. The timer delay starts when the loop returns.
  4. The timer drops the callback when it misses its deadline.
What will this print?
js
readFile("input.txt", () => {
  setTimeout(() => console.log("timer"), 0);
  setImmediate(() => console.log("immediate"));
});
  1. timer then immediate
  2. immediate then timer
  3. The order is not defined.

Fork this track to practice

Your turn

Write measureLag(intervalMs, report). It reports how late each tick of a repeating timer fires, so that you can chart event loop lag. A late tick must not shift every later tick.

javascript
export function measureLag(intervalMs, report) {
  const start = performance.now();
}

Start this Track to save your answers.

Terms

callback
A function passed to other code to run when its work is ready.