When does a timer actually run?
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 callback 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.nextTickcallbacks and then promise jobs. A timer never cuts in front of them.
The output is sync done, nextTick, promise job, timer, immediate, all at about 50 ms. The timer asked for 10 ms and got 50.
Removed: report(intervalMs);Added: report(performance.now() - start);Measure how long the timer actually waited.
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.
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.
export function measureLag(intervalMs, report) {
const start = performance.now();
}Unsaved changes
Terms
- callback
- A function passed to other code to run when its work is ready.