Event Loop
The event loop is a core concept in Node.js and JavaScript environments that enables asynchronous programming. It allows Node.js to perform non-blocking I/O operations, even though JavaScript itself is single-threaded.
When Node.js starts, it initializes the event loop and begins executing the code in the main module.
- As asynchronous operations are encountered, such as file reads, network requests, or timers, these tasks are delegated to the system kernel.
- Once the kernel completes a task, it signals Node.js to add the corresponding callback to the appropriate phase of the event loop.
Event Loop Phases
The event loop runs continuously, processing tasks in a loop. It consists of several phases, each responsible for specific types of operations.
-
Timers
- Executes callbacks scheduled by
setTimeout()andsetInterval(). - These callbacks are executed only after the specified delay has elapsed.
- Executes callbacks scheduled by
-
Pending Callbacks
- Handles almost all callbacks except for close callbacks, timers, and setImmediate() callbacks.
- Executes I/O operations like reading and writing to files.
-
Idle, Prepare
- Internal use only.
-
Poll
- Retrieves new I/O events.
- Executes I/O-related callbacks immediately if there are any.
- If no I/O events are pending, it will wait for callbacks to be added to the queue.
-
Check
- Executes callbacks scheduled by
setImmediate().
- Executes callbacks scheduled by
-
Close Callbacks
- Executes close callbacks, such as
socket.on('close', ...).
- Executes close callbacks, such as