← 中文资源

简体中文版本

事件循环延迟直方图

monitorEventLoopDelay 以纳秒记录定时器回调迟到程度:一段 50ms 的同步空转让后续 tick 集体延迟,max 直方图立刻暴露事件循环阻塞。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

all 20 ticks fired despite the burst: true
samples recorded: true
burst pushed max delay past 20ms: true

实现说明

事件循环延迟直方图的核心是函数 tick。 本示例的循环部分是 while (performance.now() - busyStart < 50)。异步部分依次 await 结果,顺序可预测。唯一的导入来源是 node:perf_hooks(Node.js 内建),暴露出 monitorEventLoopDelay、performance。

使用要点

  • 无需安装:node:perf_hooks 随 Node.js 本体提供。
  • 演示输出是带标签的(all 20 ticks fired despite the burst:、samples recorded:、burst pushed max delay past 20ms:),每个操作都会留下自己的一行标注。

常见问题

导入的模块是 npm 包吗?

不需要——node:perf_hooks 内置于 Node.js。node: 前缀就代表核心模块,项目里无需添加任何东西。

主要签名是 function tick()

核心语句

const chainDone = new Promise((resolve) => {
  setTimeout(function tick() {
    ticks += 1;
    if (ticks < 20) setTimeout(tick, 5);
    else resolve();
  }, 5);
});
setTimeout(() => {
  const busyStart = performance.now();
  while (performance.now() - busyStart < 50) {
    // spin one event loop turn
  }
}, 10);
await chainDone;

代码示例

import { monitorEventLoopDelay, performance } from "node:perf_hooks";

// monitorEventLoopDelay records how late timer callbacks run: the gap
// between the scheduled and the actual execution time, in nanoseconds
const histogram = monitorEventLoopDelay({ resolution: 10 });
histogram.enable();

// A self-scheduling timer chain keeps samples coming at a steady pace
let ticks = 0;
const chainDone = new Promise((resolve) => {
  setTimeout(function tick() {
    ticks += 1;
    if (ticks < 20) setTimeout(tick, 5);
    else resolve();
  }, 5);
});

// One synchronous burst blocks the loop, so pending timers land late
setTimeout(() => {
  const busyStart = performance.now();
  while (performance.now() - busyStart < 50) {
    // spin one event loop turn
  }
}, 10);

// The chain still finishes - delayed, not dropped
await chainDone;
histogram.disable();
console.log("all 20 ticks fired despite the burst:", ticks === 20);
console.log("samples recorded:", histogram.count > 0);
console.log("burst pushed max delay past 20ms:", histogram.max > 20_000_000);
histogram.reset();