Node.js Event Loop

The Node.js event loop is a core concept that underpins the asynchronous, non-blocking nature of Node.js.

In this tutorial, you will learn how event loop works exactly.

Introduction to the Event Loop

  1. The event loop is a fundamental part of Node.js, responsible for managing asynchronous operations.
  2. It allows Node.js to handle I/O operations efficiently and avoid blocking the execution of code.

Understanding the Call Stack

  1. The call stack is a data structure that keeps track of the currently executing functions in your code.
  2. When a function is called, it's added to the call stack. When it returns, it's removed from the stack.

Callback Queue and Message Queue

  1. The callback queue and message queue hold functions and callbacks that are ready to be executed.
  2. The callback queue is for functions like setTimeout and I/O operations.
  3. The message queue is for events like click or HTTP request.

The Event Loop Execution Cycle

  1. The event loop continuously checks the call stack and queues.
  2. If the call stack is empty, the event loop takes the first function in the callback queue and pushes it onto the call stack for execution.

Asynchronous setTimeout

console.log('Start');

setTimeout(() => {
    console.log('Timeout callback');
}, 2000);

console.log('End');

/*
Output:
Start
End
(After 2 seconds) Timeout callback
*/
    
  1. A setTimeout is set for 2 seconds to execute a callback function.
  2. While waiting for the timeout, other code continues to execute.
  3. The callback runs after the specified time, demonstrating the event loop's non-blocking nature.

Event Loop and Non-blocking I/O

const fs = require('fs');

console.log('Start reading file');

fs.readFile('example.txt', 'utf-8', (err, data) => {
if (err) throw err;
console.log('File data:', data);
});

console.log('End reading file');

/* 
Output:
Start reading file
End reading file
File data: (file content)
*/
    
  1. A file is read asynchronously using fs.readFile.
  2. While waiting for the file reading to complete, other code continues executing.
  3. When the file reading finishes, the callback is executed, showcasing non-blocking I/O.

Synchronous vs. Asynchronous

console.log('Start');

setTimeout(() => {
    console.log('Timeout callback');
}, 0);

console.log('End');

/* 
Output:
Start
End
Timeout callback
*/
    
  1. A timeout is set with a 0 millisecond delay.
  2. Even though it's set to execute immediately, it waits for the current cycle to complete.
  3. After the initial code execution, the callback is added to the callback queue and runs when the call stack is empty, demonstrating event loop behavior.