Event loop latency
- Node.js course
- Advanced
- Lesson 14/83
- 5 min
Learn event loop latency and blocking.
Event loop latency
Event loop latency is how long the event loop takes to complete one turn. High latency means the event loop is blocked; this slows down requests.
Measurement method: you schedule setTimeout(cb, 0) and measure when cb fires. The latency is the difference between when cb fires and when it was scheduled. In Node.js 16+ performance.eventLoopUtilization() is also useful.
The latency measurement pattern
A typical latency measurement: const start = performance.now(); setTimeout(() => { const delay = performance.now() - start; }, 0);. The expected delay is near zero; but if the event loop is busy it grows.
Repeating this pattern at regular intervals gives you a trend. If latency stays high, a CPU-heavy task is blocking the event loop. The fix: move that task to a worker thread.
Practice Compare elapsed time
Import performance. Assign performance.now() to a start variable. Run a short loop. Log performance.now() >= start.
Starter code
// import the module, get the timer
// assign start time to a variable
// run a short loop
// compare elapsed timeSample solution
const { performance } = require("perf_hooks");
const start = performance.now();
let sum = 0;
for (let i = 0; i < 100; i++) sum += i;
console.log(performance.now() >= start);Expected output
true
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the method name
const start = performance.____()
const start = performance.now()
Explanation: performance.now() gives the start time.
2 What does event loop latency measure?
- Dosya boyutunu
- The event loop delay Correct answer
- The network speed
- The memory usage
Explanation: Event loop latency measures the event loop's delay.
3 Match each piece to its role
| Term | Meaning |
|---|---|
performance.now() |
Start time |
latency |
Delay |
setTimeout |
Timer |
event loop |
Event loop |