javascriptroom blog

Quiz about Node.js Event Loop

The Node.js Event Loop is a fundamental concept that enables Node.js to handle asynchronous operations efficiently. It's crucial for developers to have a solid understanding of how it works. In this blog, we'll explore the Event Loop through a series of quizzes, along with explanations, common practices, and best practices.

2026-07

Table of Contents#

  1. What is the Node.js Event Loop?
  2. Quiz Questions
    • Question 1: Timers and the Event Loop
    • Question 2: Microtasks vs. Macrotasks
    • Question 3: I/O Operations and the Event Loop
  3. Common Practices
  4. Best Practices
  5. Example Usage
  6. References

What is the Node.js Event Loop?#

The Node.js Event Loop is a mechanism that allows Node.js to perform non-blocking I/O operations. It continuously checks for pending events (like I/O completion, timers expiring) and executes the corresponding callbacks. It has several phases (e.g., timers, I/O callbacks, idle, prepare, poll, check, close callbacks).

Quiz Questions#

Question 1: Timers and the Event Loop#

Question: Consider the following code:

setTimeout(() => {
    console.log('Timeout 1');
}, 0);
 
setTimeout(() => {
    console.log('Timeout 2');
}, 0);
 
console.log('Initial');

What is the order of output?

Answer: The output will be Initial, then Timeout 1, then Timeout 2. The setTimeout with a 0 delay doesn't execute immediately. The Event Loop first processes the synchronous code (the console.log('Initial')). Then, it checks the timers phase. Both timeouts are added to the timers queue. Since they have the same delay, they are executed in the order they were added.

Question 2: Microtasks vs. Macrotasks#

Question: What is the difference between microtasks and macrotasks in the context of the Event Loop?

Answer: Macrotasks (like setTimeout, setInterval, I/O callbacks) are queued in different phases of the Event Loop. Microtasks (e.g., Promise callbacks) are executed after the current macrotask and before the next macrotask. For example:

Promise.resolve().then(() => {
    console.log('Microtask');
});
 
setTimeout(() => {
    console.log('Macrotask');
}, 0);
 
console.log('Initial');

The output will be Initial, Microtask, Macrotask.

Question 3: I/O Operations and the Event Loop#

Question: How does the Event Loop handle I/O operations?

Answer: When an I/O operation (like reading a file) is initiated, Node.js hands it off to the underlying operating system. The Event Loop continues to process other events. When the I/O operation completes, the corresponding callback is added to the I/O callbacks phase queue and executed when the Event Loop reaches that phase.

Common Practices#

  • Avoid Blocking the Event Loop: Don't perform long - running synchronous operations (e.g., a large loop without yielding) as it will block the Event Loop and prevent other callbacks from executing.
  • Use setImmediate for Deferring: setImmediate is useful for deferring code execution to the "check" phase of the Event Loop. It's often used in scenarios where you want to execute code after the current phase (e.g., after an I/O operation).

Best Practices#

  • Understand Phase Order: Know the order of the Event Loop phases (timersI/O callbacksidle, preparepollcheckclose callbacks). This helps in predicting the execution order of callbacks.
  • Proper Error Handling: In asynchronous operations (like Promise - based or callback - based I/O), handle errors gracefully. Unhandled errors can lead to unexpected behavior in the Event Loop.

Example Usage#

Let's say we have a simple server that reads a file and then sends a response.

const fs = require('fs');
const http = require('http');
 
const server = http.createServer((req, res) => {
    fs.readFile('data.txt', (err, data) => {
        if (err) {
            res.statusCode = 500;
            res.end('Error reading file');
        } else {
            res.statusCode = 200;
            res.end(data);
        }
    });
});
 
server.listen(3000, () => {
    console.log('Server running on port 3000');
});

In this example, when a request comes in, the fs.readFile initiates an I/O operation. The Event Loop continues to handle other requests (if any). When the file is read (or an error occurs), the callback is executed in the I/O callbacks phase of the Event Loop.

References#