𝗨𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱𝗶𝗻𝗴 𝘁𝗵𝗲 𝗡𝗼𝗱𝗲.𝗷𝘀 𝗘𝘃𝗲𝗻𝘁 𝗟𝗼𝗼𝗽
The Event Loop is not a worker. It is a coordinator.
Many developers find the Event Loop complex. The difficulty often comes from mixing too many concepts at once. You have to track libuv, the Call Stack, Promises, and I/O all at the same time.
Here is the simple truth. The Event Loop schedules work. It does not do the work.
JavaScript runs on a single thread. This means code runs in a straight line. One task must finish before the next begins. We need a system to manage asynchronous tasks like reading files or network requests without stopping the whole program.
How it works:
The Event Loop moves callbacks from different queues into the Call Stack. Think of each phase as a line. The Event Loop is the person moving people from the line into the room.
The main phases are:
- Timers: Handles callbacks from setTimeout and setInterval.
- Pending Callbacks: Handles specific system errors like TCP errors.
- Idle and Prepare: Internal phases used by libuv. You will not use these.
- Poll: The most important phase. It retrieves new I/O events like file reads or HTTP requests.
- Check: Handles setImmediate callbacks.
- Close Callbacks: Handles closing events like socket closures.
A common mistake is thinking the Event Loop has its own Call Stack. It does not. The runtime has one single Call Stack and one microtask queue.
The process follows this flow:
- The Event Loop picks a callback from the current phase.
- It pushes that callback into the Call Stack.
- The Call Stack runs the code.
- Once the callback finishes, the engine drains the microtask queue. This is where Promises and async/await live.
- The Event Loop moves to the next phase.
If you use setTimeout(..., 0), it goes to the Timers phase. If you use setImmediate(...), it goes to the Check phase.
The heavy lifting happens in the OS kernel and libuv. The Event Loop simply tells JavaScript when it is time to react.
Source: https://dev.to/joaovictor6/event-loop-entendendo-uma-das-bases-do-node-41a