Event Loop Detailed Explanation
The Node.js event loop allows Node.js to perform non-blocking I/O operations by offloading operations to the system kernel whenever possible.
Ultimate Guide to Node.js Event Loop | Event Loop Detailed Explanation with Code Example
Concepts
1

Codebase for this lesson: https://github.com/opendevs-org/nodejs-course-youtube/tree/main/3-event-loop
The Node.js event loop allows Node.js to perform non-blocking I/O operations by offloading operations to the system kernel whenever possible. When one of these operations completes, the kernel tells Node.js so that the appropriate callback may be added to the poll queue to eventually be executed.
When Node.js starts, it initializes the event loop, processes the provided input script which may make async API calls, schedule timers, or call process.nextTick(), then begins processing the event loop.
Each phase of the event loop has a FIFO queue of callbacks to execute (timer have sorted heap). When the event loop enters a given phase, it will perform any operations specific to that phase, then execute callbacks in that phase's queue until the queue has been exhausted or the maximum number of callbacks has executed.
The different phases of the event loop include:
- timers: this phase executes callbacks scheduled by setTimeout() and setInterval().
- I/O callbacks: executes I/O callbacks deferred to the next loop iteration.
- poll: retrieve new I/O events; execute I/O related callbacks; node will block here when appropriate.
- check: setImmediate() callbacks are invoked here.
- close callbacks: some close callbacks, e.g. socket.on('close', ...).
After each phase, Node.js has an internal event loop which resolves all the process.nextTick() callbacks and another smaller event loop which executes resolved promises' then() callbacks i.e Promise.resolve().then() callbacks.