How the Event Loop Works

Nguyen Dinh Khai - Sep 15 - - Dev Community

The event loop in JavaScript is a fundamental concept that allows JavaScript to perform non-blocking operations, despite being single-threaded. It is responsible for handling asynchronous operations by managing the execution of multiple pieces of code over time.

How the Event Loop Works:

  1. Call Stack: This is where your code gets pushed and executed. When a function is called, it gets added to the call stack, and when the function completes, it is removed (popped) from the stack. JavaScript executes code in the call stack synchronously (one at a time).

  2. Web APIs: JavaScript in the browser environment provides APIs like setTimeout, fetch, DOM events, etc. These APIs handle time-consuming tasks asynchronously. When these tasks are invoked, they are executed outside the call stack by the browser.

  3. Callback Queue (Task Queue): When asynchronous operations like setTimeout or fetch complete, their callbacks are pushed into the callback queue. This is a list of functions that are ready to be executed once the call stack is empty.

  4. Event Loop: The event loop constantly monitors the call stack and the callback queue. If the call stack is empty, the event loop takes the first callback from the callback queue and pushes it onto the call stack for execution. This cycle repeats, allowing JavaScript to handle asynchronous tasks efficiently.

Please check this code below:

console.log('One');

setTimeout(() => {
  console.log('Three');
}, 1000);

console.log('Two');

Enter fullscreen mode Exit fullscreen mode

The result:

One
Two
Three

Enter fullscreen mode Exit fullscreen mode

Explanation:

  • console.log('One') is executed first and added to the call stack, then removed after execution.
  • setTimeout is called, which sets a timer for 1 second. Its callback is sent to the Web API, not directly to the call stack.
  • console.log('Two') is added to the call stack and executed next.
  • After the 1-second timer finishes, the callback (() => { console.log('Three'); }) is placed in the callback queue.
  • The event loop checks the call stack, sees it's empty, and pushes the callback from the callback queue to the call stack.
  • The callback is executed, printing Three.
. . . . . . .
Terabox Video Player