These days due to plenty of libraries, tools and other kinds of stuff that makes development life easier, a lot of developers start building their application without having a deep understanding of how things work under the hood. Javascript is one of those programming languages in which developers start working on it without having a deep understanding.

Javascript is a single thread programming language. That means it can do only one thing at a time. Javascript single thread property has its own benefits and cause.

Benefits of this are that you don’t have to worry about the complexities coming in the multi-threaded programming languages like deadlocks.

And the cause of this is that you can’t do the heavy operations like image manipulations and other CPU intensive works.

Despite these cause then why Javascript is one of the most used programming languages over the past few years. The answer to this question is that Javascript Event Loop.

Yes, Javascript Event Loop makes, javascript so much easier to use and build a scalable application on top of that.

In this tutorial, we are going to learn about the javascript event loop in simple term with detail explanation.

What is Event Loop In Javascript

In the simple term, Event Loop in javascript is a constantly running process that checks if the call stack is empty. If call stack is empty then it looks into the event queue. If the event queue has something that is waiting then it is moved to the call stacks and if not then nothing happens.

In the above paragraph, we used terms like call stacks, event queue. There are few other terms besides these which are heap, web APIs which is used to execute a javascript code.

Let’s understand these terms in details then we will have a clear idea about event loop in javascript.

Heap

Heap in the javascript is a place where objects stores when we define them in our code.

Stacks

A Stack is a data structure which works in Last In First Out(LIFO) manners. The stack holds all the javascript function call. On each call, it pushed on the top of the stack.

What does above line meaning is whenever in javascript, a function is call is pushed to the top of the stack and when another function is called then that will also put on the top of the stack and continue.

While debugging the javascript code, you always see a long list of the function in the console in the same order in which they are called like below image.

javascript event loop call stack example

Web API

Browsers have defined APIs which developers can be used to make the complex process which knows as web API. You can find the whole list of the web API from here.

Callback Queue

When a process such as XHR, setTimeout, setInterval, promises to finish its job then they pushed into the callback queue. The callback queue is triggered by the event loop process after our stack is empty. When our stacks have no function call then a process is popped out from the callback queue and pushed it to stack.

So after knowing about the above terms, now you can know-how javascript event loop works and how javascript process each function call under the hood.

event loop in javascript diagram example

Understand JavaScript Event Loop With Example

Till now, we learn about the event loop in theoretical way only. Now, let’s see how the event loop works in javascript with plenty of examples.

Example 1: No Async Code

console.log("first");
console.log("second");
console.log("third");

In the above code, we are simple console the three states, first, second, and third. They simply printed in the console in the same order as they are written.

first
second
third

Now let’s understand the above code in details

  1. When JS engine runs the code then the initial state is empty for call stack, web API, callback queue.
  2. Now, as soon as js engine init, console.log(“first”) is added to the call stack.
  3. console.log(“first”) is executed.
  4. console.log(“first”) removed from the call stack.
  5. Now, console.log(“second”) is added to the call stack.
  6. console.log(“second”) is executed.
  7. After execution, console.log(“second”) removed from the call stack.
  8. Now the last line of the code, console.log(“third”) is added in the call stack.
  9. console.log(“third”) is executed.
  10. console.log(“third) is removed from the call stack

Example 2: With setTimeout() Function

The first example is very straight forward, now take another example which has setTimeout in the code.

const f1 = () => console.log("first");

const f2 = () => console.log("second");

const f3 = () => console.log("third");

f1();
setTimeout(f2,1000);
f3();

Above code looks similar like example 1 but the output of this example is different from the first one. Below is the output of the above program.

first
third
second

Strange ??? Let’s understand how this output came. Before going to the explanation of the above program, I thought, you must have a good understand of the above diagram which I tagged earlier in this post.

  1. When JS engine runs the code then the initial state is empty for call stack, web API, callback queue.
  2. Now, as soon as js engine init, console.log(“first”) is added to the call stack.
  3. console.log(“first”) is executed.
  4. console.log(“first”) removed from the call stack.
  5. setTimeout() function is added to the call.
  6. The next statement (setTimeout() with callback exec() and 1000ms wait time) is pushed into the call stack and execution starts. setTimeout function uses a Browser API to delay a callback to the provided function. The frame (with setTimeout) is then popped out once the handover to the browser is complete (for the timer).
  7. While timer runs, console.log(“second”) is pushed to the call stack. We don’t have to wait for functions setTimeout, because they are provided by the browser, and they live on their own threads. For example, if you set setTimeout to 4 seconds, you don’t have to wait 4 seconds – wait happens elsewhere.
  8. console.log(“third”) is executed.
  9. console.log(“third”) removed from the call stack.
  10. Now call stack is empty. The callback queue will push the console.log(“second”) into the call stack. That is why even though the delay provided in the setTimeout() was 0 seconds, the callback to exec() has to wait till the execution of all the frames in the call stack is complete.
  11. console.log(“second”) is executed.
  12. console.log(“second”) removed from the call stack.

Example 3: With ES6 Promise

const f1 = () => console.log('f1')

const f2 = () => console.log('f2')

const f3 = () => {
  console.log('f3');
  setTimeout(f2, 0)
  new Promise((resolve, reject) =>
    resolve('I am Promise')
  ).then(resolve => console.log(resolve))
  f1();
}

f3();

//output

'f3'
'f1'
'I am Promise'
'f2'

In the above code, we are using three functions f1, f2 and f3. f1 and f2 are doing console and f3 have three other things within it. f3 first console f3 then calling the function f2 with setTimeout and then doing a promise request.

As in the output, we can see promise result printed before the setTimeout function. The reason behind this is es6 introduces the concept of the job queue which is used by the promises. It’s a way to execute the result of an async function as soon as possible, rather than being put at the end of the call stack.

That’s a big difference between Promises and plain old asynchronous functions through setTimeout() or other platform APIs.

Conclusion

Hope you got the basic idea of how javascript event loop works. There is a lot more going on under the hood and this is just the basic explanation of the event loop in javascript.

Something else to have in mind is that this explanation is in the context of the V8 JavaScript Engine. It’s the engine behind Chrome and is also used in Node.

If you have any thoughts then share that in the comment section. I will try to reply as soon as possible. If you think this works for you then don’t forget to share this with your friends and in social media.

Happy Coding…

Codecademy Web Development
Pin It