0
0
Node.jsframework~8 mins

Event loop phases and timer execution in Node.js - Performance & Optimization

Choose your learning style9 modes available
Performance: Event loop phases and timer execution
MEDIUM IMPACT
This concept affects how quickly Node.js processes timers and callbacks, impacting responsiveness and throughput of server-side applications.
Scheduling repeated tasks with timers
Node.js
function heavyTask() {
  return new Promise(resolve => {
    setImmediate(() => {
      for(let i = 0; i < 1e8; i++) {}
      resolve();
    });
  });
}

async function runInterval() {
  while(true) {
    await heavyTask();
    console.log('Interval task done');
    await new Promise(r => setTimeout(r, 1000));
  }
}

runInterval();
Offloads heavy work to next event loop phase and uses async delays to avoid blocking timers.
📈 Performance GainKeeps event loop responsive, timers fire on time, and other callbacks run smoothly.
Scheduling repeated tasks with timers
Node.js
setInterval(() => {
  // heavy synchronous task
  for(let i = 0; i < 1e8; i++) {}
  console.log('Interval task done');
}, 1000);
Heavy synchronous work inside setInterval blocks the event loop, delaying other callbacks and timers.
📉 Performance CostBlocks event loop for hundreds of milliseconds each interval, causing delayed timer execution.
Performance Comparison
PatternEvent Loop BlockingTimer AccuracyCPU UsageVerdict
Heavy synchronous code in setIntervalBlocks event loop for 100+ msTimers delayedHigh CPU spikes[X] Bad
Async heavy task with setImmediate and awaitNo blocking, event loop freeTimers fire on timeBalanced CPU usage[OK] Good
Rendering Pipeline
Node.js event loop cycles through phases: timers, pending callbacks, idle/prepare, poll, check, and close callbacks. Timer callbacks run in the timers phase if their scheduled time has elapsed.
Timers phase
Poll phase
Check phase
⚠️ BottleneckBlocking synchronous code in any phase delays subsequent phases and timer execution.
Optimization Tips
1Avoid heavy synchronous code inside timer callbacks to prevent event loop blocking.
2Timer callbacks run in the timers phase only after their scheduled delay has passed.
3Use asynchronous patterns to keep the event loop free and timers firing on time.
Performance Quiz - 3 Questions
Test your performance knowledge
What happens if a timer callback contains heavy synchronous code?
AIt runs in parallel without blocking.
BIt speeds up timer execution.
CIt blocks the event loop, delaying other timers and callbacks.
DIt causes the event loop to skip phases.
DevTools: Performance
How to check: Record a CPU profile while running your Node.js app with timers. Look for long tasks blocking the event loop and delayed timer callbacks.
What to look for: Long blocking tasks in the flame chart and timer callbacks not firing at expected intervals indicate poor timer handling.