namaste-javascript-notes

Episode 15 : Asynchronous JavaScript & EVENT LOOP from scratch

Note: Call stack will execeute any execeution context which enters it. Time, tide and JS waits for none. TLDR; Call stack has no timer.

WebAPIs

None of the below are part of Javascript! These are extra superpowers that browser has. Browser gives access to JS callstack to use these powers. Event Loop 2 Demo

Event Loops and Callback Queue

Q: How after 5 secs timer is console?

Q: Another example to understand Eventloop & Callback Queue.

See the below Image and code and try to understand the reason: Event Loop 5 Demo Explaination?

Q: Need of callback queue?

Ans: Suppose user clciks button x6 times. So 6 cb() are put inside callback queue. Event loop sees if call stack is empty/has space and whether callback queue is not empty(6 elements here). Elements of callback queue popped off, put in callstack, executed and then popped off from call stack.


Behaviour of fetch (Microtask Queue?)

Let’s observe the code below and try to understand

console.log("Start"); // this calls the console web api (through window) which in turn actually modifies values in console. 
setTimeout(function cbT() { 
  console.log("CB Timeout");
}, 5000);
fetch("https://api.netflix.com").then(function cbF() {
    console.log("CB Netflix");
}); // take 2 seconds to bring response
// millions lines of code
console.log("End"); 

Code Explaination:
* Same steps for everything before fetch() in above code.
* fetch registers cbF into webapi environment along with existing cbT.
* cbT is waiting for 5000ms to end so that it can be put inside callback queue. cbF is waiting for data to be returned from Netflix servers gonna take 2 seconds.
* After this millions of lines of code is running, by the time millions line of code will execute, 5 seconds has finished and now the timer has expired and response from Netflix server is ready.
* Data back from cbF ready to be executed gets stored into something called a Microtask Queue.
* Also after expiration of timer, cbT is ready to execute in Callback Queue.
* Microtask Queue is exactly same as Callback Queue, but it has higher priority. Functions in Microtask Queue are executed earlier than Callback Queue.
* In console, first Start and End are printed in console. First cbF goes in callstack and "CB Netflix" is printed. cbF popped from callstack. Next cbT is removed from callback Queue, put in Call Stack, "CB Timeout" is printed, and cbT removed from callstack.
* See below Image for more understanding

Event Loop 6 Demo Microtask Priority Visualization Event Loop 7 Demo

What enters the Microtask Queue ?

Some Important Questions

  1. When does the event loop actually start ? - Event loop, as the name suggests, is a single-thread, loop that is almost infinite. It’s always running and doing its job.

  2. Are only asynchronous web api callbacks are registered in web api environment? - YES, the synchronous callback functions like what we pass inside map, filter and reduce aren’t registered in the Web API environment. It’s just those async callback functions which go through all this.

  3. Does the web API environment stores only the callback function and pushes the same callback to queue/microtask queue? - Yes, the callback functions are stored, and a reference is scheduled in the queues. Moreover, in the case of event listeners(for example click handlers), the original callbacks stay in the web API environment forever, that’s why it’s adviced to explicitly remove the listeners when not in use so that the garbage collector does its job.

  4. How does it matter if we delay for setTimeout would be 0ms. Then callback will move to queue without any wait ? - No, there are trust issues with setTimeout() 😅. The callback function needs to wait until the Call Stack is empty. So the 0 ms callback might have to wait for 100ms also if the stack is busy.


Observation of Eventloop, Callback Queue & Microtask Queue [GiF]

microtask 1 Demo microtask 2 Demo microtask 3 Demo microtask 4 Demo microtask 5 Demo microtask 6 Demo


Watch Live On Youtube below:

Asynchronous JavaScript & EVENT LOOP from scratch in JS Youtube Link