How is the event processing cycle structured in the Event Loop model in Node.js?
sobes.tech AI
Answer from AI
Event Loop in Node.js is a mechanism that allows executing non-blocking operations despite the single-threaded nature of the environment.
Main stages of the event processing loop:
-
Timers: callbacks scheduled with
setTimeoutandsetIntervalare executed if their time has elapsed. -
Pending Callbacks: processing of some system callbacks.
-
Idle, Prepare: internal Node.js operations.
-
Poll: fetching new I/O events; executing I/O callbacks if they are ready.
-
Check: executing callbacks scheduled via
setImmediate. -
Close Callbacks: handling socket closures and other resources.
The loop repeats, checking the event queue and calling the appropriate callbacks. If the queue is empty, the Event Loop may wait for new events or terminate.
Example:
setTimeout(() => console.log('timeout'), 0);
setImmediate(() => console.log('immediate'));
console.log('start');
The output will be:
start
immediate
timeout
Because setImmediate is called at the Check stage, and setTimeout at the Timers stage of the next cycle.