Event loop in javascript
If you love javascript you’ve need to learn this. One of the deeper aspects of JavaScript is it’s Event Loop. Its possible for many developers to work for years and still not understand event loop in javascript. However, through this blog post I’m hoping to shed some light into what the event loop is and how it’s really not that complicated.
How Chrome’s V8 engine treats a javascript code
Its job is to go through the lines of JavaScript code in an application and process them one at a time. That’s right — one at a time, meaning that JavaScript is single-threaded. It process line by line.
A line of JavaScript that happens to take a really long time to return may block the code written after it.
Imagine that you’re on a web site and click on a button and then it just hangs there. You try clicking on other buttons but nope, nothing happens. The most likely culprit of this (assuming no bugs) is the button click triggered some JavaScript code to execute but it’s blocking.
Call Stack can also be 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 line in call stack and executed it in LIFO method (Last in First Out). In short call stack is a data structure that records and identifies where we are in the program.
So what do you think how does the engine how to process these lines of javascript code one at a time is big time question???
The answer is- It uses the call stack.
You can think of a call stack like entering an elevator — the first person who enters the elevator is the last person to exit the elevator, whereas the last person to enter is the first to exit.
Let’s see an example.
var firstEventLoop = function () {
console.log("Yo people i am first one!!");
};
var secondEventLoop = function () {
firstEventLoop();
console.log("Yo people i am second one!!");
};
secondEventLoop();
Now let’s see what’s going on in the call stack when we execute above file, main function (anonymous function) of the file is pushed in call stack (shown in below figure).

Now in above code secondEventLoop
function is invoked:
After secondEventLoop
is called, the call stack will appear as below:

Invoking secondEventLoop
causes firstEventLoop
function to be invoked
After firstEventLoop
function is invoked, the call stack will appear as below:

Invoking firstEventLoop function, console.log.Now there are no more codes available to execute in firstEventLoop function so firstEventLoop function is removed from call stack.

Execution continues in secondEventLoop function, secondEventLoop function console.logs.After that there are no more codes available to execute hence secondEventLoop function is removed from the call stack.

Finally there are no more lines of code to execute in this file so anonymous function of file is removed from the call stack.
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.
function printMe1 () {
console.log("Hello Javascript");
};
function printMe2(){
setTimeout(printMe1(),2000);
console.log("Hey I am the first to be printed");
}
printMe2();
By executing the above code, first it will log “Hey I am the first to be printed
” 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.

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

Execution continues with printMe2() and print ‘It’s my function’ — string in console and printMe2 is removed from call stack. Now there are no more items in call stack so anonymous function is removed from call stack.
And call stack is empty as shown below:

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

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(row);
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(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.
Let me dive more into Javascript Event Loop.
Let’s see this how it works with previous example.

Previously we saw that when setTimeout function pushes in call stack with printMe1 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.

We see that once the callback function (printMe1()) 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 printMe1 function is triggered and moved into message queue.
Two seconds later:

The printMe1() function is moved from event table to message queue.
One process that continuously check 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 call stack and from call stack it gets executed.
This whole process is known as EVENT LOOP.

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