Components of a Web Browser

  • Call Stack: A stack that holds functions to be executed sequentially in JavaScript.
  • Web API: APIs provided by the web browser for performing asynchronous tasks, such as AJAX and setTimeout.
  • Task Queue: Also known as the Callback Queue, it stores callback functions passed from the Web API.
  • Event Loop: Checks if the Call Stack is empty; if it is, it moves tasks from the Task Queue to the Call Stack.
setTimeout(() => console.log("Async Hi hun"));
console.log("Hello! World");
// Hello! World
// Async Hi hun

Even though asynchronous code is executed first, we can see it printed later.

  1. The setTimeout function is executed and added to the Call Stack.
  2. The setTimeout function is not handled by the JavaScript engine but by the Web API (in the case of Node.js, the Timers module). Once the timeout duration has passed, the Web API passes the callback function to the Task Queue.
  3. Next, the console.log on the second line is added to the Call Stack. The console.log in the Call Stack is executed immediately, and the string “Hello! World” is printed to the console.
  4. At this point, the JavaScript Event Loop constantly checks if the Call Stack is empty. After executing console.log, the Event Loop confirms that the Call Stack is empty.
  5. Once the Event Loop detects that the Call Stack is empty, it moves the callback function from the Task Queue to the Call Stack to execute it. The string “Async Hi Hun” is then printed.

Once all tasks are completed, both the Call Stack and Task Queue are empty.