Event Loop

The event loop is core to the performance of Node.js, helping it to perform asynchronous and non-blocking operations

Event Loop: How Does Asynchronous JavaScript Actually Work? | by Divyojyoti  Ghosh | JavaScript in Plain English

The event loop constantly checks if the call stack is empty.

If the call stack is empty, it looks into the Callback Queue for pending callbacks.

If there are callbacks, the event loop pushes them onto the call stack for execution.

let's try to understand it with an example

function wait2Second() {
  console.log("this fucntion will wait for 2 second");
}
function quick() {
  console.log("this function will be executed quickly");
}
setTimeout(() => {
  wait2Second()
}, 2000);
quick()

// output 
// this function will be executed quickly
// this fucntion will wait for 2 second

The quick() function is called first.

Call Stack:
- quick()

The quick() function is executed and logs "this function will be executed quickly."

setTimeout (Asynchronous Operation):

  • The setTimeout function is encountered, and it initiates an asynchronous operation. The wait2Second function is scheduled to be executed after a delay of 2000 milliseconds (2 seconds).

      Call Stack:
      (empty)
    
  • The call stack is empty because quick() has completed. The event loop checks for pending tasks in the Callback Queue.

  • wait2Second in Callback Queue:

    • After 2000 milliseconds, the wait2Second function is moved from the Callback Queue to the call stack.

    •   Call Stack:
        - wait2Second()
      

The wait2Second function is executed, logging "this function will wait for 2 seconds."

Final State:

  • The call stack is now empty, and there are no more pending tasks in the Callback Queue.

  •   Call Stack:
      (empty)
    

The event loop has completed its cycle.

The event loop is responsible for handling asynchronous operations and ensuring that their associated callbacks are executed when the call stack is empty.

In this example, the quick() function doesn't wait for the wait2Second function to complete. It continues execution immediately after initiating the asynchronous operation.

The event loop enables non-blocking behavior, allowing JavaScript to handle time-consuming tasks without freezing the entire program.