Pergunta de entrevista da empresa ZeMoSo

what is event loop and its phases?

Resposta da entrevista

Sigiloso

14 de jul. de 2025

The event loop is a core component of JavaScript's concurrency model, enabling asynchronous, non-blocking operations in a single-threaded environment. It continuously checks and processes events from the event queue, ensuring that tasks like user interactions, timers, and I/O operations are handled efficiently without blocking the main thread. Phases of the Event Loop The event loop operates in a series of phases, each handling specific types of tasks. Below are the main phases, as defined in environments like Node.js (which has a more detailed model compared to browsers): Timers Phase: Handles callbacks from timers, such as setTimeout and setInterval. A timer callback is executed if the specified delay has elapsed. Example: If setTimeout(callback, 1000) is set, the callback is queued here after 1 second. Pending Callbacks Phase: Executes I/O callbacks that were deferred from previous cycles, such as certain asynchronous operations that are not immediately resolved. Common in Node.js for handling system-level operations. Idle, Prepare Phase (Node.js-specific): Internal phase for Node.js to handle preparatory tasks, not directly accessible to developers. Used for internal bookkeeping and setup. Poll Phase: Retrieves new I/O events and executes their callbacks (e.g., file reads, network requests). If no timers are scheduled, the event loop may wait here for new events. If the queue is empty and no more tasks are expected, the event loop may exit (in Node.js). Check Phase: Handles setImmediate callbacks, which are executed immediately after the poll phase. Useful for running tasks after the current I/O cycle. Close Callbacks Phase: Executes callbacks for closing resources, such as socket.on('close', ...) or cleanup tasks when streams or connections are closed. console.log("Start"); setTimeout(() => console.log("Timeout"), 0); Promise.resolve().then(() => console.log("Promise")); console.log("End");