The event loop helps Node.js handle many tasks without waiting for each to finish. It keeps your app fast and responsive.
0
0
Event loop mental model in Node.js
Introduction
When you want to run multiple tasks without blocking the program.
When handling user requests in a web server.
When working with timers or waiting for files to load.
When you want to run code after a delay or when an event happens.
When managing asynchronous operations like reading data from a database.
Syntax
Node.js
Node.js runs JavaScript code in a single thread. The event loop checks for tasks to run and executes them one by one. It handles callbacks from timers, I/O, and promises.
The event loop runs continuously while your program is active.
It uses queues to manage different types of tasks.
Examples
This shows how a timer callback waits 1 second before running, while the rest runs immediately.
Node.js
setTimeout(() => {
console.log('Timer done');
}, 1000);
console.log('Start');process.nextTick runs its callback before other queued tasks, right after the current code.
Node.js
console.log('First'); process.nextTick(() => { console.log('Next Tick'); }); console.log('Last');
Promise callbacks run after the current code but before timers, showing microtask queue behavior.
Node.js
Promise.resolve().then(() => {
console.log('Promise resolved');
});
console.log('After promise');Sample Program
This program shows the event loop order: synchronous code runs first, then promise callbacks, then timer callbacks.
Node.js
console.log('Start'); setTimeout(() => { console.log('Timeout callback'); }, 0); Promise.resolve().then(() => { console.log('Promise callback'); }); console.log('End');
OutputSuccess
Important Notes
The event loop lets Node.js do many things without waiting for each to finish.
Microtasks like promises run before timers in the event loop.
Understanding the event loop helps avoid bugs with timing and order of code execution.
Summary
The event loop runs tasks in order to keep Node.js fast and non-blocking.
Synchronous code runs first, then microtasks like promises, then timers and I/O callbacks.
Knowing this helps you write better asynchronous code.