Skip to main content

Command Palette

Search for a command to run...

♻️ JavaScript: Event Loop♻️

Updated
•4 min read•View as Markdown
♻️ JavaScript: Event Loop♻️
C

Frontend Dev 🚀 | JavaScript ♥ | ReactJs ♥ | Next JS | Featured Technical Writer✍️

Oh, boi🕺🏼the event loop. It’s one of those things that every JavaScript developer has to deal with in one way or another, but it can be a bit confusing to understand at first.

In one single sentence, let’s define what is the event loop:

Moving events from the task queue to the call stack is called the “event loop”

What is a javascript event loop?🤔

The actual Javascript event loop is really simple.

But in order to understand the job of the event loop, we need to clear the fog around the other three: 🧘‍♀️

  • Call stack
  • Web APIs
  • Callback Queue

Web APIs(browser).png

Let's go through each of this one by one and see what they are.

Call stack 🏳️‍🌈

I have a complete article on call stack you can check it out.😃

As a single-threaded programming language Javascript has only one call stack. This means that only one thing can be executed at a time. A call stack is simply a place where these executable contexts are placed in order for getting executed. Call stack follows the LIFO principle (Last In First Out).

Let's look at an example to make this clear.

function square(b) {
   return b * b ; 
 }

 function cube(x) {
   return x * square(x)
 }

 console.log(cube(8));

The above snippet is an example of defining a cube function, which is calling a square function, to find the cube of a number passed in the argument. But how does this work in the call stack? Let's understand step by step:

  1. When we call the console.log() line, this code/function is pushed into the call stack.
  2. Now the above console.log() function is called the cube function, hence this function is pushed into the stack.
  3. After this the cube function is calling the square function, and now this would be pushed into the stack.
  4. Now once the square function is executed, and the result is returned, then the square function is popped out of the stack.
  5. Since at this step, we have got the square function result, so cube function would be executed and popped out of the call stack.
  6. At last, the console.log() would be executed and this function would be popped out of the stack and the stack would now be empty.

Step 1.png

Javascript Web APIs🗺️

These are the additional functionality, that helps us perform some additional tasks which cannot be run using the main thread. However, since our JavaScript runtime is single-threaded, it can export some tasks to the WEB APIs which helps us to respond to multiple threads.

Examples of some web APIs are:

  • DOM
  • Ajax (Network requests)
  • setTimeout()

For instance, setTimeout() is called, and the browser delegates the task to a different thread to calculate the time interval specified in the argument of the setTimeout() method, and once done this tread would then call the desired function in callback stack.

Since JavaScript is single-threaded, the browser has the capability of delegating the task in multiple threads. But how does the event loop help in these executions?🤔

DOM(document).png

But now we are good to go ahead with Event Loop.

Event Loop ♻️&& Event Queue🚶🚶🚶🚶

Since we know that Web APIs delegate some of the tasks to different threads, on completion of these tasks, how the main or desired functions are sent to the call stack.

An event Queue is a special queue, which keeps track of all the function queues, which are needed to be pushed into the call stack. The event queue is responsible for sending new functions to the track for processing. The queue data structure is required to maintain the correct sequence in which all operations should be sent for execution.

Let's take an example,

In the following example, we are using a setTimeout function, which will log the "Executed" string after 3000 milliseconds.

setTimeout(function(){
    console.log("Executed";)
  }, 3000);

Now when a setTimeout operation is processed in the call stack. On its execution, it calls a web API which fires a timer for 3000 milliseconds. After 3000 milliseconds has been elapsed, the web API places the callback function of setTimeout in the event queue.

Here need to mention that, just placing our function does not necessarily imply that the function will get executed. This function has to be pushed into the call stack for execution and here the event loop comes into the picture.

The event loop waits for the function stack to be empty, once the call stack is empty this will push the first function from the event queue to the call stack, and in this way, the desired function will be called.

Thus event loop works in a cyclic manner, where it continually checks whether or not the call stack is empty. If it is empty, new functions are added from the event queue. If it is not, then the current function call is processed.

Comments (13)

Join the discussion
S

keep writing

1
C

Thank you and keep reading..

N

Simple good start up article for javascript developer

1
K

This is just a great and super simplified explanation.

C

thank you

A

Fantastic! 👍🔥

C

Thank you❤❤❤❤...and Thank you for putting so much effort for us in the Bootcamp.

C

I have understood the generals of this for quite a while, but could not explain it. Now I better can!

I wonder if this is why you cannot use a while loop to block the thread while waiting for an asynchronous task to be completed. The browser delegates that task to another thread, and when that promise is resolved, it will place the response/callback in the event queue. However, if a while loop is ongoing (like while (true)) then it will keep iterating forever, placing its iterations into the call stack continuously.

Thus, the call stack will never be empty for the promise in the event loop to reach the call stack and proceed with the code.

Is my thought process correct here?

S

This is worth reading🚀🚀.

But there is also another type of queue along with Event Queue Microtask queue / Priority queue.

1
R

Amazing

2
M

Great explanation! Thank you for this!

C

Really happy...😊stay tuned for more..

W
Wojtek X4y ago

Just awesome 😀 keep writing and learning ✌️

C

Thank you😊

M

More power to u !!! 😊🔥🔥🔥

C

Thank you batchmate..🥰

1