JavaScript is a single-threaded synchronous language. JS engine uses call-stack to manage execution. but what if we have to perform asynchronous task?

Event Loop

Event Loop
Namaste JS event loop gif

In case of event listeners

document.getElementById("btn").addEventListener("click", function cb() {
  console.log("callback");
});

for above code; when this line is executed,

  1. Web API (window object) attaches click event listener to the callback function and pushes this callback to the callback queue upon occurrence of event “click”.
  2. Event loop constantly check call stack and callback queue, if there is a callback in callback queue, it pushes to stack to execute it.
Event Loop

In case of fetch() API

fetch("http://api.netfilex.com)
	  .then(function cbf(){
		  console.log("cb netfilx")
	  })
  1. web API’s environment registers callback function cbf
  2. callback goes to Micro-task queue( same as callback queue but is has higher priority).

What can come inside micro-task queue

Promises and mutation observers goes inside micro-task queue.

Starvation

suppose there is endless callbacks in micro-task queue, so callback queue’s function is never executed. this is starvation.