Event Loop โžฐ in JavaScript ๐ŸŒŒ

Event Loop โžฐ in JavaScript ๐ŸŒŒ

ยท

5 min read

Event Loop, this particular topic is faced by every JavaScript developer on daily basis but very few actually know how this works.

So, what is an event loop? ๐Ÿค”

Event loop is an element that takes something like a function from Callback queue and places it into the Call Stack.

But before moving further into the event loop, we need to clear the basics first.

Let's talk about a few topics:

  1. Call Stack
  2. Web APIs
  3. CallBack Queue

Call Stack ๐Ÿงฑ

As we know JavaScript is a single-threaded programming language which means it has only one call stack or execution stack. Having only one call stack means only one function or process can be executed at a time.

Let's see with an example.

As we know Global Context gets executed first and when the Js engine finds any function it performs the Functional Context Execution.

gif.gif

First, the Global Context Execution is done then when the Js engine finds functions it performs the Functional Context Execution.

Then the function1() is executed and it is placed inside the call stack above the Global Execution Context.

After that inside function1(), function2() is called thus function2() is placed above function1() in the call stack.

Once function2() is competed it pops off the from the call stack and after that as fucntion1() gets it also pops off the call stack and finally the Global Execution Context also pops off the call stack and the stack is emptied.

This is how the call stack works in JavaScript.

The JavaScript contains the call stack and call stack is not limited to this much only but for the time being we just need to know this much about it.

Web APIs โšก ๐Ÿ”ฅ ๐Ÿ’ง

By default, JavaScript does not have the ability to manipulate DOM, fetch data from external servers, execute functions after some time, etc.

These features are provided by Web API thus we can say that Web APIs are like superpowers that are provided to the JavaScript by the browser.

Some of the web APIs are:

  • setTimeout()
  • HTML DOM
  • fetch()
  • local storage
  • location

Whenever a function like setTimeout() is called, it is stored in a different thread till the interval passed to setTimeout() finishes, once it is finished that callback function is sent to the callback queue where it waits till the time comes for its execution and then it is moved to the call stack.

Remember, JavaScript is a single-threaded language but the browser can handle multiple threads at the same time and so multiple processes can run simultaneously.

This movement of functions from the callback queue to the call stack is managed by Event Loop.

Now, let's take a deep dive and understand what is the event loop.

Event Loop โžฐ

Let's take an example first

console.log("start");

setTimeout(() => {
  console.log("Hello there I am a setTimeout Function");
}, 3000);

console.log("end");

In the above example, first console.log("start") gets executed. After that comes the setTimeout which takes a callback function and executes the callback after the given interval in our case it is 3000 ms. After 3000 ms the callback function is placed inside the callback queue, but it will not get executed. The callback will get executed only when the function moves to the call stack and this movement of function from callback queue to call stack is managed by the Event loop.

Now till the setTimeout interval passes, the browser moves ahead with the code and executes console.log("end"). Once the interval of 3000 ms is completed, the callback function goes into the callback queue.

Now the event loop checks if the call stack is empty, only if the call stack is empty, the event loop moves the function from the callback queue to the call stack where it gets executed. The functions are moved from the callback queue one by one only when the call stack is empty.

This is how the event loop works. You can see the flow in the below gif. Untitled design (1).gif

Microtask Queue ๐Ÿ”ฌ

There is one more type of queue in which the browser delegates the functions, it is known as Microtask queue.

A Microtask queue is similar to a callback queue, but it stores the callback functions with higher priority.

Now, the question arises which functions have higher priority?

So, the callback functions which work with promises like fetch() have more priority than callback functions like setTimeout().

Let's have a look at how the Microtask queue comes into play.

console.log("start");

setTimeout(function timeOut()  {
  console.log("Hello there I am a setTimeout Function");
}, 3000);

fetch("http://google.com").then(function result() {
  console.log("Success");
})

console.log("end");

Untitled design (2).gif

Here first the console.log("start") is executed after that setTimeout() callback is called which is stored inside the callback queus after the interval time is completed i.e after 3000 ms the callback is entered into the callback queue where it waits for its turn.

After that the fetch function runs, if the promise is resolved the callback is sent into the microtask queue where it waits for the call stack to get emptied.

Till then console.log("end") is executed, once everything is executed from the global execution context and the call stack is emptied, the event loop takes the fetch callback from the microtask queue first and puts it into the call stack where fetch callback gets executed.

After executing the fetch callback, the call stack again gets emptied and the event loop takes the setTimeout callback from the callback queue and put it into the call stack and executes the callback function.

In this way, the microtask queue is incorporated and event loops work.

This was my article on Event loop, callback queue and microtask queue.

Hope this added some value to your JavaScript knowledge.

Thanks for reading this article. ๐Ÿ˜ƒ

ย