Экраны

Lesson/lessons/:id

Перейти к содержимому

Цикл событий

9 мин
Перевод устарел
Оригинал обновился.

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
Плохо
Удалено: report(intervalMs);
Хорошо
Добавлено: 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.

01A timer expires during a synchronous loop. Why does its callback not interrupt the loop?
02What will this print?
js
readFile("input.txt", () => {
  setTimeout(() => console.log("timer"), 0);
  setImmediate(() => console.log("immediate"));
});

Отвечено: 0 из 2

Попробуйте сами

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();
}

Есть несохранённые изменения

Термины

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