What is the poll phase in the NodeJS event loop?
Get an in-depth understanding of polling phases in node js event loops which is a commonly asked question in interviews.
What is the event loop in Node.js?
The event loop is a core feature of Node.js. It allows you to learn about Node's asynchronous processes and non-blocking I/O. It explains the mechanisms that make Node such a common, efficient, and effective modern system.
When Node.js starts, it initializes the event loop, processes the given input script (or drops into the REPL) which may perform async API calls, schedule timers, or call process.nextTick(), then starts processing the event loop.
There is a FIFO queue of callbacks to execute in each phase. While each process is unique in its own way, when the event loop enters one, it will perform any operations relevant to that phase before executing callbacks in that phase's queue until the queue is empty or the maximum number of callbacks has been executed. The event loop will switch to the next phase when the queue is full or the callback limit is reached, and so on.
Phases in brief:
- timers: callbacks scheduled by setTimeout() and setInterval() are executed in this phase.
- pending callbacks: runs I/O callbacks that have been delayed until the next loop iteration.
- idle, prepare: internally used.
- poll: fetch new I/O events; execute I/O related callbacks (almost all with the exception of close callbacks, the ones scheduled by timers, and setImmediate()); the node will block here when required.
- check: setImmediate() callbacks are called here.
- close callbacks: some close callbacks such as socket.on('close', ...).
As Node.js starts executing your index.js file, or some other application entry point, the Event Loop begins.
These six phases combine to form a tick, which is a cycle or loop. When there is no more pending work in the Event Loop, or when process.exit() is manually named a Node.js process exits. A program can only run for as long as tasks are queued in the Event Loop or on the call stack.
Assume that you have written the following code:
For the event loop:
When the event loop is in the poll phase of its iteration, the entire code will be executed.
The poll phase has two main functions:
- Figuring out how long it should block and poll for I/O
- Then, process events in the poll queue.
If there are no timers scheduled when the event loop reaches the poll phase, one of two things will happen:
- If the poll queue is not empty, the event loop will iterate through its callback queue, running them synchronously until the queue is exhausted or the system-dependent hard limit is met.
- If setImmediate() was not used to schedule scripts, the event loop would wait for callbacks to be added to the queue before executing them.
The event loop will search for timers whose time limits have been reached until the poll queue is empty. If one or more timers are ready, the event loop returns to the timers phase to perform the callbacks for those timers. If the poll queue is empty, it normally blocks and waits for any in-flight I/O operations to finish before executing their callbacks. The poll phase, however, will come to an end if timers are set. Any microtasks that are needed will be executed, and the event loop will continue to the check process.
Poll Phase Callbacks
During the poll phase, all non-blocking I/O request callbacks are executed. Microtasks are executed immediately on MacOS if they are scheduled during a poll phase callback (rather than waiting for the poll phase to complete before running microtasks). Microtasks run after the mainline and at the end of each phase of the event loop.
The poll phase becomes idle when the callback queue for the poll phase is empty.
If there are no timers set, the poll phase waits for any pending I/O requests to finish before executing their callbacks.
The event loop advances to the check phase if any timers have been set.
Without using any protocols like WebSocket or Server Side Events, long polling is an efficient way to establish a highly stable link with the server. This technique is used by Node.js.
Long Polling, in other words, works on top of the traditional client-server model. The client sends the request, and the server responds when it has new and specific information; until that time, the link remains open.
The client may submit another request as soon as the server responds, and the server will return a query when data is available. When the client app closes and the server sends a request, this process begins.
Long polling in Node JS is a mechanism in which the client sends data to the server, but the server only responds until it has received complete data.
Simultaneously, the client's link is open, and it is waiting for the server to reply with data before sending another query.
Long Polling in Node.js can be configured on the client-side here. During downtime or when making new requests to the server, the client generates an event loop.
Regular Polling vs Long Polling
Periodic polling is the simplest way to get information from the server. To accomplish this, use the setInterval function in conjunction with an Ajax call to the server every x seconds. Now, the server recognizes that the client is connected and sends the client a response that is currently open.
The procedure continues to function normally. However, it has a number of serious flaws, which are as follows:
- Messages are sent to the client after a 10-second interval.
- When new data is unavailable, the whole process fails, but every request is sent to the server and receives null responses.
This approach works well in the case of small services, but it certainly requires an update.
When compared to standard polling, long polling is much preferred. It is simple to execute and provides knowledge quickly.
Here's how it works:
- A request is sent to the server by the client (assume it's a browser).
- The link is kept open, and the server does not respond until it has identified specific data.
- The server sends new data to the client if and when it becomes available.
- The browser can now submit a new request almost immediately.
We hope that after reading this article, you have a better understanding of polling. Polling in Node.js can be used by a dedicated Node.js developer for their web development projects to reap the benefits.