Sobes.tech
Junior — Middle

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:

  1. Timers: callbacks scheduled with setTimeout and setInterval are executed if their time has elapsed.

  2. Pending Callbacks: processing of some system callbacks.

  3. Idle, Prepare: internal Node.js operations.

  4. Poll: fetching new I/O events; executing I/O callbacks if they are ready.

  5. Check: executing callbacks scheduled via setImmediate.

  6. 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.