Loading lesson path
Concept visual
Formula
The event loop is what makes Node.js non - blocking and efficient.It handles asynchronous operations by delegating tasks to the system and processing their results through callbacks, allowing Node.js to manage thousands of concurrent connections with a single thread.
Node.js follows these steps to handle operations: Execute the main script (synchronous code) Process any microtasks (Promises, process.nextTick) Execute timers (setTimeout, setInterval)
Formula
Run I/O callbacks (file system, network operations)Handle close events (like socket.on('close'))
Example: Event Loop Order console.log('First');
setTimeout(() => console.log('Third'), 0);
Promise.resolve().then(() => console.log('Second'));
console.log('Fourth');Sync code runs first ('First', 'Fourth') Microtasks (Promises) run before the next phase ('Second') Timers execute last ('Third')
The event loop processes different types of callbacks in this order:
setTimeout, setInterval
Formula
: Completed I/O operationsFormula
: Retrieve new I/O eventssetImmediate callbacks
: Cleanup callbacks (like socket.on('close') )
Between each phase, Node.js runs microtasks (Promises) and process.nextTick callbacks.
Example: Event Loop Phases console.log('1. Start');
// Next tick queue process.nextTick(() => console.log('2. Next tick'));
// Microtask queue (Promise)
Promise.resolve().then(() => console.log('3. Promise'));
// Timer phase setTimeout(() => console.log('4. Timeout'), 0);
// Check phase setImmediate(() => console.log('5. Immediate'));
console.log('6. End');Formula
This shows the priority order: sync code > nextTick > Promises > Timers > Check phase.The event loop enables Node.js to handle thousands of concurrent connections with a single thread, making it perfect for:
Node.js uses an event loop to handle async operations
Microtasks (Promises) run before the next event loop phase