Engineering 8 min read

Event Loop with Javascript

Javascript is easy to use through its base is profound. Due to the complex design, it’s a bit difficult to understand. Event Loop is one of the deeper aspects of Javascript, let’s discuss this aspect and I hope this blog post will help you understand about event loop better. How exactly does the event loop work? It is not too complex. However before we move to the event loop, let’s have a look at the basic duty of the Javascript Engine.

Javascript Engine:
There are several javascript engines available like Spider Monkey, Chakra, V8, etc. But the most popular version is Google Chrome’s V8 engine. V8 is Google’s open-source Javascript engine and it is not limited to the browser, it also plays a role at server-side via NodeJs.

Let’s see what exactly does the javascript engine does?
Well, its duty is to go through the code line by line in an application and process them one at a time, which means javascript executes sequentially & runs in a single thread of execution.

Let’s understand it better with a small code snippet.


When we execute the above code, Javascript will start processing the code line by line and one at a time providing the output as displayed in the above example.

So how does javascript engine know how to process a single line of javascript at a time?

It uses a Call Stack. Call Stack is like a shopping bag, the first item that enters in the shopping bag is the last item to exit and vice-versa. Javascript engine adds all lines in the call stack and executed it in the LIFO method (Last in First Out). In the short call stack is a data structure that records and identifies where we are in the program.

Let’s see an example for better understanding.

code snipet2

Now let’s see what’s going on in the call stack when we execute the above file, the main function (anonymous function) of the file is pushed in the call stack (shown in the below figure).

Initial State:

anonymous function

Now in the above code displayAverage function is invoked:

After displayAverage is called, the call stack will appear as below:

call stack

Invoking displayAverage causes average function to be invoked

After the average function is invoked, the call stack will appear as below:

call stack1

Invoking average causes calculateAverage function to be invoked.

After calculateAverage function is invoked, the call stack will appear as below:

call stack 2

Invoking calculateAverage function, returns calculated value i.e. (10+20)/2 = 15

Now there are no more codes available to execute in calculateAverage function so calculateAverage function is removed from call stack.

After calculateAverage function returns, the call stack will appear as below:

call stack 3

Execution continues in average function, average function returns result which is received by calculateAverage functions. After returning average function there are no more codes available to execute hence average function is removed from the call stack.

After average function returns, the call stack will appear as below:

call stack 4

Execution continues in displayAverage and ’15’ is print in console. After this there are no more codes available to execute in displayAverage function and hence the displayAverage function is removed from the call stack.

After displayAverage function returns, the call stack will appear as below:

anonymous function 1

Finally there are no more lines of code to execute in this file so anonymous function of file is removed from the call stack.

I hope now we got the idea how call stack works in the javascript engine.

Now let’s move to ahead.

Well we all are familiar with setTimeout function right? In setTimeout function we can call function. Well that function itself is an asynchronous callback function.

Let’s have a look at the below example.

code snipet3

By executing the above code, first it will log “It’s my function” string in console and then ‘Hello javascript’ string – I hope it makes sense?

Now let’s check what’s going on in call stack for above code.

call stack 5

What is going to happen after setTimeout is in call stack which has printData as callback function. As we all knows that printData function does not run immediately, it runs 2 seconds later so it can’t push printData function in call stack right now so somehow it disappears from call stack.

The call stack will appear as below:

call stack 6

Execution continues with myFunction and print ‘It’s my function’ – string in console and myFunction is removed from call stack. Now there are no more items in call stack so anynymous function is removed from call stack.

And call stack is empty as shown below:

call stack 7

Two seconds later magically printData function will appear in call stack as shown below:

print data

It executes and logs ‘Hello javascript’ in console. You might be surprised how does that happen? Here event loop comes in on concurrency.

We discussed earlier that Javascript run-time can do one thing at a time but now we are talking about concurrency. Well it’s true that javascript run-time can do only one thing at a time, we can’t make an Ajax call while running another code, we also can’t do a setTimeout while running another code but we can do all of these through Browser. Browser allows you to make an Ajax call while running another code and it can also do a setTimeout while running another code.

Doing setTimeout and making an Ajax request does not live in Javascript run-time but browser handles it as a web API. Browser is aware about such kind of process and we can get the results with its callback function.

An event loop runs in a single thread unlike the threaded model where for every request new thread is spawned, which means you don’t get the overhead.

Because all different things are happening in the same thread, you cannot block. This means you cannot wait for something to happen because that would block the whole thread. Instead you define a callback that is called once the action is complete. This is usually referred to as non-blocking I/O.

example for blocking I/O:

row = db_query(‘SELECT * FROM users’);


print(‘It will print after user result print’);

In above code, Execution will be paused until and unless it returns result of db query then remaining code will be execute. So first it will print row (result of users query) and then it will print “It will print after user result print” string.

Now lets see same example but slight changes.

example for non-blocking I/O:

db_query(‘SELECT * FROM users’, function (row) {



print(‘It will print before user result print’);

In above example uses anonymous functions like we  used in JavaScript all the time. JS makes heavy use of events, and that’s exactly what callbacks are about. Once the action is complete, an event is fired which triggers the callback. This is why it is often referred to as an evented model or also asynchronous model. So in example execution will not wait for result of query, It fires query and continue with other line of code. Once result will produce from query then it call its callback and print. First it will print  “It will print before user result print” string and then print row (result of users query).

The implementation of this model uses a loop that processes and fires these events. That’s why it is called an event queue or event loop.

Examples of event queue frameworks include:

  • EventMachine (Ruby)
  • Tornado (Python)
  • js (V8 server-side JavaScript)

Let me dive more into Javascript Event Loop.

Let’s see this how it works with previous example.

event loop process 1

Previously we saw that when setTimeout function pushes in call stack with printData which is a callback function, it disappeared from call stack. When setTimeout is executed, browser places setTimeout’s call back function into an event table. As it’s a web API it has nothing to do with current javascript runtime so it passes to event table to register this function and execute it when specific event happens (in this case after 2 seconds later).


When the event happens, the event table will move the function in message queue table or you can say callback queue table.

Let’s see what happens after setTimeout function is executed.

event loop process 2

We see that once the callback function (printData()) is moved to event table, nothing is blocked in call stack. Browser doesn’t wait for 2 seconds and it continues execution from call stack. Here next line is myFunction, it’s invoked and printed “It’s my function” in console and removed from call stack hence there are no more lines in call stack so anonymous function is also remove from call stack, call stack is now empty.

Event table constantly monitors whether any of the events are triggered. If yes, then that function is moved in message queue or call back queue. In our case after 2 second printData function is triggered and moved into message queue.

Two seconds later:

event loop process 3

The printData() function is moved from the event table to the message queue.

One process that continuously checks whether the call stack is empty. If the call stack gets empty it checks if there are any functions waiting to be invoked. If yes, then the first function in the message queue table moves into the call stack and from the call stack, it gets executed.

This whole process is known as EVENT LOOP.

Let’s see the whole event loop process using the below figure.

event loop process 4

In the above example we can see that the printData function is moved into call stack and executed. It prints “Hello javascript” string in console. Everything is empty now.

Chintan Pandya

I am passionate about working on progressive technologies like NodeJs and AngularJS. I am always eager to learn new technologies and ready to dig deep into it to work on innovative concepts.


Similar Stories

Engineering 4 min read

TensorFlow vs PyTorch vs Keras: The Differences, Similarities, and Utilities

TensorFlow vs Pytorch vs Keras might sound foreign to you now, but...

read more

Top-tier Data Visualization Tools for 2022

Data visualization tools is a term that we did not know about...

read more
Engineering 5 min read

AngularJS vs ReactJS: The Classic Contemporary Comparison

As of 2022, there are roughly 24 JavaScript frameworks available to code...

read more