Event Loop Delay Histogram
Record how late timer callbacks run with monitorEventLoopDelay: a synchronous burst blocks the loop and shows up as nanosecond-scale max delay.
Code
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();Output
Captured from a sandboxed run of this snippet in the build pipeline.
all 20 ticks fired despite the burst: true
samples recorded: true
burst pushed max delay past 20ms: trueHow it works
Event Loop Delay Histogram reduces to the function tick.
The loop while (performance.now() - busyStart < 50) is the only repeated construct. Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. The only import source is node:perf_hooks, a Node.js built-in, exposing monitorEventLoopDelay, performance.
Points of care
- The dependency surface is just
node:perf_hooks, and that one is built into Node.js.
Using it
Entry signature: function tick()
Output from the demo is tagged (all 20 ticks fired despite the burst:, samples recorded:, burst pushed max delay past 20ms:); tracing a label leads to the call that emitted it.
Key statements
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;
Interactive Tools for This Topic
FAQ
- Is the imported module an npm package?
- No — `node:perf_hooks` is built into Node.js. The `node:` prefix marks core modules, so there is nothing to add to a project.
Report a problem with this exampleOpens a pre-filled issue on GitHub.