Lesson 25 of 50 – Event Loop

50% Completed
50%

Event Loop in Node.js

The Event Loop is an important part of Node.js. It helps Node.js handle asynchronous operations without blocking the main JavaScript thread while waiting for many I/O operations to complete.

Remember: Node.js executes JavaScript callbacks on its main JavaScript thread by default. The Event Loop coordinates when asynchronous callbacks can run.

1. What Is the Event Loop?

The Event Loop is a mechanism used by Node.js to manage asynchronous callbacks. It allows Node.js to continue handling other work while operations such as timers and file or network I/O are pending.

For example, Node.js can:

  • Execute ordinary JavaScript statements.
  • Schedule timers using setTimeout().
  • Handle file and network operations asynchronously.
  • Run callbacks when their scheduled work is ready.
Example: Simple Event Loop
console.log("First");

setTimeout(function() {
    console.log("Second");
}, 1000);

console.log("Third");
Output:
First
Third
Second

The timer callback runs after the synchronous statements. The delay is approximately one second, not an exact guarantee.

2. How Does the Event Loop Work?

When Node.js executes a program, synchronous statements run first. Asynchronous operations can be scheduled, and their callbacks become eligible to run when the relevant operation or timer is ready.

Basic Execution Flow
  1. Node.js starts executing the JavaScript code.
  2. Synchronous statements run in order.
  3. Asynchronous operations are scheduled.
  4. The Event Loop coordinates callback execution.
  5. Ready callbacks run when the JavaScript thread can execute them.
The Event Loop does not make every operation run in parallel. JavaScript callbacks normally run one at a time on the main thread. Some work, such as certain file-system operations, can use Node.js's worker pool or other operating-system facilities.

3. Synchronous and Asynchronous Code

Synchronous code executes in sequence. An asynchronous operation can allow the program to continue while it waits for a result.

Example: Synchronous Code
console.log("A");
console.log("B");
console.log("C");
Output:
A
B
C
Example: Asynchronous Code
console.log("A");

setTimeout(function() {
    console.log("B");
}, 0);

console.log("C");
Output:
A
C
B

Even with a delay of zero milliseconds, the timer callback does not interrupt the synchronous statements.

4. Event Loop and setTimeout()

The setTimeout() function schedules a callback to run after at least the specified delay, when the Event Loop can execute it.

Example: Timer Execution
console.log("Program started");

setTimeout(function() {
    console.log("Timer completed");
}, 2000);

console.log("Program continues");
Output:
Program started
Program continues
Timer completed

The program does not wait synchronously for the timer. The timer callback runs later, after the delay has elapsed and the Event Loop can execute it.

5. Event Loop and Promises

Promise callbacks, such as those passed to .then(), are scheduled as microtasks. In ordinary Node.js code, pending Promise microtasks are processed before the Event Loop continues to later timer callbacks.

Example: Promise and Timer
console.log("Start");

setTimeout(function() {
    console.log("Timer");
}, 0);

Promise.resolve().then(function() {
    console.log("Promise");
});

console.log("End");
Output:
Start
End
Promise
Timer

The synchronous code runs first, followed by the Promise microtask and then the timer callback in this example.

6. What Are Event Loop Phases?

Node.js organizes Event Loop work into phases. Each phase handles certain kinds of callbacks.

Phase Purpose
Timers Runs eligible callbacks scheduled by setTimeout() and setInterval().
Pending Callbacks Runs certain system-level I/O callbacks deferred to this phase.
Idle, Prepare Internal Node.js processing.
Poll Processes many I/O-related callbacks and waits for I/O when appropriate.
Check Runs callbacks scheduled using setImmediate().
Close Callbacks Handles certain close events, such as socket close callbacks.
Note: Promise microtasks and process.nextTick() callbacks are not separate Event Loop phases in this table. Their scheduling and execution have their own rules.

7. Difference Between setTimeout() and setImmediate()

Both functions schedule callbacks, but they are associated with different parts of the Event Loop.

Example: setTimeout() and setImmediate()
setTimeout(function() {
    console.log("Timeout callback");
}, 0);

setImmediate(function() {
    console.log("Immediate callback");
});

When run directly from the main module, the order of these two messages is not guaranteed across all circumstances.

Inside an I/O callback, setImmediate() is generally executed before a zero-delay timer scheduled in that callback.

8. What Is process.nextTick()?

process.nextTick() schedules a callback to run after the current JavaScript operation finishes, before the Event Loop continues to its next phase.

Example: process.nextTick()
console.log("One");

process.nextTick(function() {
    console.log("Two");
});

console.log("Three");
Output:
One
Three
Two

The nextTick callback does not interrupt the current synchronous code. Node.js processes it afterward.

9. Why Is the Event Loop Important?

Benefits of the Event Loop
  • Helps Node.js handle many I/O operations efficiently.
  • Allows other JavaScript work while asynchronous I/O is pending.
  • Supports timers, Promises, and callback-based APIs.
  • Helps build responsive servers and network applications.
  • Works with asynchronous patterns such as async and await.
Important: Long-running synchronous JavaScript can block the Event Loop and delay other callbacks. CPU-intensive work may need to be moved to worker threads or another process.

10. Practical Assignment

Practice these programs:
  1. Print three messages using synchronous code.
  2. Use setTimeout() to print a message after two seconds.
  3. Compare the output of synchronous and asynchronous code.
  4. Write a program using Promise.resolve() and setTimeout().
  5. Use process.nextTick() and observe the output order.
  6. Compare setTimeout() and setImmediate().
  7. Explain how the Event Loop helps a Node.js server handle I/O.

Test Your Knowledge – Event Loop

Select the correct answer for each question.

1. What is the main purpose of the Node.js Event Loop?
2. What is the output order of the following code?
console.log("A");
setTimeout(() => console.log("B"), 0);
console.log("C");
3. Which function schedules a callback for the Check phase?