0
0
Node.jsframework~5 mins

Event loop phases and timer execution in Node.js

Choose your learning style9 modes available
Introduction

The event loop lets Node.js do many things at once by managing tasks in steps called phases. Timers run in a special phase to schedule code after a delay.

When you want to run code after a delay or repeatedly at intervals.
When you need to understand why some callbacks run before others in Node.js.
When debugging why some asynchronous code runs later than expected.
When optimizing performance by knowing how Node.js handles tasks in order.
Syntax
Node.js
setTimeout(callback, delay)
setInterval(callback, delay)

setTimeout runs the callback once after the delay (in milliseconds).

setInterval runs the callback repeatedly every delay milliseconds.

Examples
This runs the message once after 1 second.
Node.js
setTimeout(() => {
  console.log('Hello after 1 second');
}, 1000);
This prints the message every 2 seconds until stopped.
Node.js
setInterval(() => {
  console.log('Repeats every 2 seconds');
}, 2000);
Even with 0 delay, the timeout runs after current code finishes.
Node.js
console.log('Start');
setTimeout(() => {
  console.log('Timeout');
}, 0);
console.log('End');
Sample Program

This program shows how timer callbacks run after the current code finishes, in the timers phase of the event loop. The shorter delay callback runs first.

Node.js
console.log('Phase 1: Start');

setTimeout(() => {
  console.log('Timer callback runs in timers phase');
}, 100);

setTimeout(() => {
  console.log('Another timer callback');
}, 50);

console.log('Phase 1: End');
OutputSuccess
Important Notes

Timers run in the timers phase of the event loop, after the current code completes.

Even a 0 ms delay means the callback waits until the timers phase, so it runs after synchronous code.

Callbacks with shorter delays usually run before longer delays, but exact timing depends on system and event loop state.

Summary

The event loop has phases; timers run in the timers phase.

setTimeout schedules code to run after a delay in the timers phase.

Even zero delay callbacks run after current synchronous code finishes.