Team egg🥚 or Team chicken🐔?

VANDANA GUPTA
6 min readAug 20, 2021

--

The age-old riddle of was it the egg that came first or the chicken, has always blown our heads and led to arguments. Well here comes our EVENT LOOP to solve this riddle.

So, why wait ⌛??

Take a coffee ☕ and let me give you a brief before understanding the event loop.

JavaScript is single-threaded which means code execution is done one at a time. If any code takes a long time to execute, it will block anything that needs to be executed. To have a visual representation of single and multi-threading, you can go through this URL https://codersblock.com/assets/demos/web-workers/single.html.

In order to understand the event loop, we will first understand basic terms that are related to it.

Stack

It's a simple data structure with push() and pop() methods. Whenever the code encounters a function call, that function is pushed into the stack and when the function is finished, it pops out of the stack.

Heap

Heap is a place where every object is allocated a certain memory.

Queue

For now understand that it is a simple data structure that processes messages based on the FIFO principle (First in, first-out).

Visual representation of the code execution:

🟣🔵🟡                   index.jsfunction nextSample() {
console.log("Next sample function");
}
function sample() {
console.log("sample function");
nextSample();
}
sample();
Call Stack ( Part of the JS engine)

Let’s go through all the steps of the execution of the above code :

  1. In the code, sample() call takes place first so it is pushed into the stack.
  2. Then, console.log() within the sample() is encountered and it is pushed into the stack and after the execution, it is popped out.
  3. The next line has nextSample() call within the sample() so it is pushed into the stack.
  4. After that,console.log() within the nextSample() is encountered and it is pushed into the stack and after the execution, it is popped out.
  5. Finally,nextSample() has no more other lines of code and its execution is completed hence it is popped out of the stack.
  6. At last,sample() execution is also completed and hence it is also popped out of the stack.

You can try the visualizer for the above code from any of the two https://bit.ly/2XrTxVX or https://bit.ly/2VZ4iPg.

The above code will be executed without taking a lot of time. But what if a scenario arises where a browser sends an HTTP request and there is a lot of waiting time till the response comes? Will the user interacting with it be not frustrated?

Consider you went to a restaurant 😃which serves your favorite food 🍔🍟🍕🍜 and you are hungry 🤤 and the chef takes a lot of time ⌚to prepare your food. Will you be not exhausted😑😕😖 in the meantime? Arrrrr….😡

Relax ☺and take another sip of coffee ☕

Now here comes our browser and node to help our dear JavaScript🆘. In this blog, we will focus on browser only so the browser basically provides Web API like(setTimeout() ,setInterval())which is not a part of JavaScript but built on the top of the core JS language.These Web APIs help to create async/non-blocking behavior.

JavaScript engine which does code execution doesn’t work in isolation but works inside an environment. So browser comes with a javascript engine that provides a Javascript runtime environment and helps in the execution of the code. Let’s see how the overall structure of JavaScript runtime looks with the environment.

Javascript runtime environment

Web APIs are asynchronous and it does the work in the background meanwhile there is further execution of other code. A callback function is given to the web API whose responsibility is to execute the code once the web API is done with its execution.

If a function has Web API, javascript give that control to the Web API with a callback function and move to other lines of the code. Once the Web API work is done, it just binds the result of that to the callback function and then a message is passed into a queue, and since this message has a callback function associated so it's known as callback queue. Now how it is executed in the stack is a part of the event loop.

An event loop has one responsibility -:

  1. It checks if there is any message pending in the callback queue and if found that the stack is empty, it pushes the callback function to the stack(one callback function at a time).

Let’s take one example and you can try the below code here https://bit.ly/3yb2UWZ

🟠🟣🟡                    index.jsfunction sample() {
console.log("Start of the sample()");
setTimeout(firstCallbackForSetTimeout, 3000);
setTimeout(secondCallbackForSetTimeout, 3000);
console.log("End of the sample()");
}
function firstCallbackForSetTimeout() {
console.log("First setTimeout is excuted.");
}
function secondCallbackForSetTimeout() {
console.log("Second setTimeout is excuted.");
}
sample();
Output🟢
Start of the sample()
End of the sample()
First setTimeout is excuted.
Second setTimeout is excuted.
Visualization for the above code in the tool given by Phillip Roberts

As discussed, the above code runs the exact same way.setTimeout with the callback is passed to Web API and in the meantime, javascript executes other lines of code. The first setTimeout work is done ( delay of 3000ms) and then it is passed to queue and similarly for the second setTimeout. Now queue works on the FIFO concept and the event loop finds that the stack is empty and callbacks in the queue are present. It moves the first-come callback to the stack and then the next callback.

Finally, the wait is over.

We are all set to solve the riddle.

Take your last sip of coffee☕

Here is the code which will solve the riddle 😁

🟠🟣🟡                 index.jsfunction solveRiddle()
{
setTimeout(function(){ console.log('Chicken')}, 0);
new Promise(function(resolve, reject) {
resolve();
})
.then(function(){
console.log('Egg');
});
}
solveRiddle();

You must be thinking the output will be Chicken and then Egg.

But no, The output is ‘Egg’ and then ‘Chicken. Meanwhile, Team Egg be happy, you won 😂 . The age-old riddle of was it the egg that came first or the chicken is solved😁 .

The above scenario occurred because of two more things — : Macro-task and Micro-task. These two tasks occupy their own queue instead of mixing with the message queue. An example of a Macro-task is ( setTimeout,setInterval,setImmediate) and Micro-task is (Promises,process.nextTick).

The event loop does the following in such -:

  1. Initially, the event loop takes exactly one Macro-task from the Macro-task queue and executes it.
  2. Next, the Event loop goes to the Microtask queue and executes all the microtask one after the other.
  3. Finally, it goes to the Macro-task queue.

You must be wondering then how come in the above code,promise is executed before setTimeout?

In Javascript, no code is allowed to execute until an event occurs. At the execution of Javascript code, the JS engine basically takes the whole content and wraps it within the function. And associates this function with the event ‘start’ or ‘launch’.As the event is enqueued to the macro-task queue .‘Start’ or ‘launch’ event is emitted by the JS engine and it enqueues into the macro-task queue. So, this is the first Macro-task that gets executed. Hence setTimout is not executed before the promise.

TL;DR

  1. About Stack, queue, heap
  2. About Javascript runtime environment
  3. About Event loop
  4. About Microtask and Macro-task Queue
  5. Team Egg won ( Shh secret 🤐 I was already on their side. 😅)

Thank you ✨✨

Happy coding !!

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

VANDANA GUPTA
VANDANA GUPTA

Written by VANDANA GUPTA

An inquisitive person. A learner.

Responses (2)

Write a response