What is Event Loop?

The event loop is a key concept in JavaScript's concurrency model, responsible for handling asynchronous operations. It's what allows JavaScript to perform non-blocking I/O operations despite being single-threaded.

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.

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).

  • 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.

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

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

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.