Javascript Event Loop for dummies 🤡
Tags: javascript, programming, async, promises
Published: 2021-02-08 22:03:25

If someone who is not in the tech industry (a Muggle 😆) asks you what JavaScript is, could you define it? Well, you could say something like this:

> "Javascript is an **asynchronous**, **single-threaded** and **non-blocking** language which uses some tools like a **call stack**, an **event loop**, a **callback queue** and some other **APIs** for **concurrency**".

But BRUUUH??!!

![Confused GIF](https://media.giphy.com/media/toB3AnUDkqE3GENKx0/giphy.gif)

That sounds like a dangerous spell in Harry Potter that would send your enemy straight to hell, doesn't it? But don't worry, I don't like when people use some complicated words to say barely nothing either. So let's go through each of those bizarre words.

- **Call stack**: that is where our tasks (functions encountered in the code) are stacked. When we encounter a function, we push it to the stack and when we return from that function, we pop it off the stack (LIFO)
- **Single-threaded**: in simple words, JavaScript can only do one thing at a time (one call stack). One element (function) in the stack is executed at a time.
- **Non-blocking**: it means that whenever a "slow" task (I'll tell you what i mean by that later) is encountered in the call stack, it doesn't block the execution of the following tasks.
- **Asynchronous**: The non-blocking behavior we explained above is done by using **asynchronous callbacks** which means that we run the "slow" task, give it a callback (an action to do when it's done), and run that callback later.
- **Callback queue**: basically the place where the callbacks are queued (FIFO) waiting for their turn to be called by our MVP, the call stack 😎
- The famous **Event Loop**: that's what this whole article is about. Basically, it's the process of  checking if the call stack is empty, and if so, taking off the first element (the first callback) in the queue (if it is not empty, of course 🙄) and pushing it to the stack for it to be executed.

Easy Peasy, isn't it 😌?! NO?! Alright, I admit, that's a lot of words. So let's see a straightforward example to explain all of this.

---

Let's admit we're in a restaurant where some **orders** are already cooked and are quick to serve by the **waitress**, and some other are harder to make and are going to take time to be cooked by the **chef** (the "slow" tasks I was talking about 😉). We imagine that whatever the chef cooks, he puts it on his big table for the waitress to take it (It's my article, I do what i want, okay? 😒)

![Restaurant example image](https://dev-to-uploads.s3.amazonaws.com/i/bcyir11p5bqkal01pdld.png)

Now we suppose that our waitress has 3 orders on her list. The quick orders are represented in white and the "slow" ones are represented in blue. They are **stacked** in her list.

![Stacked functions GIF](https://dev-to-uploads.s3.amazonaws.com/i/sxceheoh9t2y18pssw8n.gif)

The order on the top of the list (a hamburger) is then served to client 4 and get's removed from the list when it's done 

![Get hamburger GIF](https://dev-to-uploads.s3.amazonaws.com/i/mue80zgnyai9n968vaof.gif)

We can notice that the next order is a slow order. So the waitress gives it to the chef who cooks it, and puts the bowl of cooked salad on his table, for the waitress to serve it later.

![Get salad GIF](https://dev-to-uploads.s3.amazonaws.com/i/5rtbyez3k7trxwrjipwb.gif)

Meanwhile, the waitress takes care of the next order (a cup of juice) which is quick, and serves it to the client 4 (he's quite hungry 😅)

![Get juice GIF](https://dev-to-uploads.s3.amazonaws.com/i/pl14qjezikwdwincroyt.gif)

When it's done, the waitress notices that her list is empty. So she checks the chef's table to see if there is any meal on it.

![Check table GIF](https://dev-to-uploads.s3.amazonaws.com/i/a1vqlespaz0fri7541nx.gif)

If so, she takes that meal, and serves it the corresponding client (in this case, she serves a delicious bowl of salad the client 3)

![Salad Bowl GIF](https://dev-to-uploads.s3.amazonaws.com/i/68zqxk6aoi9pq2kht7fc.gif)

Her list being still empty, she checks the chef's table once again and see's that there's nothing on it. Thus, she can clock out and go home 🎉.

![Second table check GIF](https://dev-to-uploads.s3.amazonaws.com/i/1xijvge18o933rzlkeiy.gif)

That's it!! That's how JavaScript works. You still can't make the connection between the example and the weird words above 😩? Alright, let's see, with the same animation, how the following code is going to be executed.

```jsx
console.log("Hello!");
setTimeout(function cb() {
	console.log("Slow!!");
}, 7000);
console.log("Bye!");
```

First of all, let's place our weird words to where they belong in the animation

![Event loop image](https://dev-to-uploads.s3.amazonaws.com/i/v908v9655k5ccabrx14p.png)

Now let's see how it works

![JS Process GIF](https://dev-to-uploads.s3.amazonaws.com/i/mo2h5r746hsicv0jjeht.gif)

- The `main()` function specified here is just the main thread of our code.
- Each function is pushed to the stack when it is called, and popped off it when it returns something.
- Our slow function (`setTimeout()`) is not handled by the javascript engine, but by some WebAPIs in the browser which will push the resulting callback into the queue when it's done.
- Meanwhile, the functions in the stack continue to get executed. Whenever the stack is empty, the event loop checks if the callback queue is empty, takes the first element in it (our callback function) and push it to the call stack
- The execution continues until there's nothing left in the call stack or in the callback queue.

See? It's not that complicated, right? 

---

I hope this article helped you understand better the famous event loop and made you feel better with javascript. It is fundamental to understand these concepts in order to avoid some strange behaviors when you write asynchronous functions. If it still seems confusing to you, I recommend [this excellent video of Philip Roberts](https://www.youtube.com/watch?v=8aGhZQkoFbQ&ab_channel=JSConf) explaining it:

Feel free to reach out to me if you have any questions:

- Github: [nushen96](https://github.com/nushen96)
- Twitter: [papidiagne30](https://twitter.com/papidiagne30)

Peace out!! ✌🏾