Event Loop in node.js
Event Loop in node.js
Node.js is an event-based platform. All node.js applications utilize "Single Threaded Event Loop Model" engineering to deal with numerous simultaneous clients. This implies everything occurs in Node.js is the response to an event.Node.js is a single strung application, however, it can help simultaneousness help of occasion and callbacks. Each API of Node.js is a no concurrent and single-strung, they utilize Async work calls to look after simultaneousness. The headliner circle is single - strung, however, a large portion of the I/O works keep running on discrete strings, in light of the fact that the I/O APIs in node.js are no concurrent/non-blocking. Occasions and callbacks seem to be comparable yet the distinctions lie in the way that callback capacities are considered when a no concurrent work returns though occasion taking care of chips away at the observer pattern
Event Loop Explanation:
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.
The following diagrams show a simplified overview of the event loop’s order of operations.
Each phase has a FIFO queue of callbacks to execute. When the event loop enters in 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. When the queue has been exhausted the event loop will move to the next phase and so on. Since operations can be scheduled more operations and new events processed in the poll phase are queued by the kernel, poll events can be queued while polling events are being processed.
- timers: this phase executes callbacks scheduled by setTimeout() and setInterval().
- pending callbacks: executes I/O callbacks deferred to the next loop iteration.
- idle, prepare: only used internally.
- poll: retrieve new I/O events; execute I/O related callbacks (almost all with the exception of close callbacks, the ones scheduled by timers, and setImmediate()); node will block here when appropriate.
- check: setImmediate() callbacks are invoked here.
- close callbacks: some close callbacks, e.g. socket.on('close', ...).
Node.js Event Example:
Run the above code: