Blog
>
Technology

Event Loop in Javascript

Abhishek Kovuri
I
March 26, 2021

As we know that Javascript is synchronous. To achieve async calls we normally use promises, callbacks and other profound techniques. But to understand callbacks in-depth, we need to know how Javascript actually process the code.

Key takeaways from this story:

  1. Heap, Stack and Queue.
  2. How they are associated with the event loop?

Heap, Queue and Stack.


Heap, Queue and Stack

Heap

In Javascript, everything is considered to be objects and Heap is a place where every object is allocated with a certain memory and it is mostly unstructured, unlike Queue and Stack.

Queue

Every message(or)every piece of code that is executable is considered. It is known that the queue follows the FIFO approach where older frames are executed first.

Stack

Suppose, we have a function which in turn dependent on the other function. Here, the dependent function is pushed to stack at the bottom and the other function on which the first function is dependent will move to the top of the stack. It is known that the stack follows the LIFO approach.

To be more precise, Stack comes into play in runtime while Queue processes your executable code.

Now coming to a practical example, how these are associated with event loop while executing our code in runtime.

How they are associated with the event loop?

Let’s dive deep and understand how our code gets executed by Javascript.

Problem Statement:

A function that takes two numbers and produces an average of them.

Average of two numbers

Event Loop

So, whenever getAverage() gets triggered, Queue moves it to stack,
when the stack starts executing it, it encounters the getSum() function on which current function is dependent so it moves getSum() to the top of the stack and starts its execution, Once it returns, getSum() gets popped out and then getAverage() uses the returned value and gives the output.

Finally, Stack is empty waiting for the queue to push new items which are to be executed.

I hope this example helped you to understand the basics of the event loop.

Summarising the Concept

As soon as the event-triggered, When calling getAverage(), a first frame is created containing getAverage’s arguments and local variables. When getAverage calls getSum, a second frame is created and pushed on top of the first one containing getSum’s arguments and local variables. When getSum returns, the top frame element is popped out of the stack (leaving only getAverage’s call frame). When getAverage returns, the stack is empty.
The queue has a separate check on the stack and passes messages into it whenever it is empty.

Great success 😃 !!!

Now let’s together jump into some async functions.

How does the Event loop work with Asynchronous functions?

So how event loop does this? let’s understand how async calls are made.

As a Frontend Engineer, we make an API call using fetch, Axios, etc to the Backend where it takes some time to process our request and send the response which is retrieved and used with the help of callbacks, promises
So, what we think here is JS is blocked until the API gives us the response right!. But all these are syntactic sugar 😆 which is a kind of hallucination that JS is blocked and is waiting for that API to return.
But JS never do it.
Javascript only runs on the main thread and it is Never blocking. so, what it means? It never waits for a certain block of code to execute but process with other lines of code. For example:

Asynchronous function

So here setTimeout() function is running on a different thread and waits until the main thread’s execution is finished console.log which is after the setTimeout() gets printed.

Now let’s check how the event loop actually does it from the background.

So, whenever the above function is triggered, It will move to the queue.
From the queue, it moves to the stack.
setTimeout() gets executed in the stack and it runs in a different thread as there is some delay to get that executed but by that time console.log will be pushed into the stack and it executes in the main thread. Once it’s finished the execution, setTimeout which is waiting for the main thread to free gets executed after 2 sec.

This is how the event loop works for asynchronous functions.

By this time, we know how the event loop works with synchronous and asynchronous code right!.

Let’s test our understanding.

Event loop

Most of us might think while loop gets executed for 1 sec and later on setTimeout() will set a = false and the execution gets finished. But this is wrong and the answer blew my mind.
Trust me! this was one of the greatest questions that I came across.
The answer is “hello” gets printed and it never ends.
why???
As I said earlier, setTimeout() executes in the different thread once it gets executed, it will wait for the main thread to get finished. here, the main thread is while-loop which starts the execution but there is no breaking condition to end while-loop as setTimeout() is waiting for the main thread to finish. As a result, the console is filled with “hello”.

Interesting!! Isn’t it?

Concluding my blog here.
Give it a clap if you find it useful.
Until Next Time, Happy Learning 😃
Bye!!

For more information on the event loop
https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop


Javascript

About Quinbay

Quinbay is a dynamic one stop technology company driven by the passion to disrupt technology today and define the future.
We private label and create digital future tech platforms for you.

Digitized . Automated . Intelligent