Event Loop
Published: 2021-05-19 17:01:56

`Disclaimer: This article is all about event-loop. It may have soo many dependency articles or too little. But It will confuse you like christopher nolan movies. So, Save your brains✌`

Let's Begin 🚀
![Let's Begin](https://media.giphy.com/media/26wkP6n7c8fQJbhVS/giphy.gif)

# EventLoop

In a nutshell it's a loop. But differ from other loops i.e., from movies or traditional loop(for, while). Because, you can't write this eventloop. In nature it's declarative. I know you won't get nothing with the definition above 🤷‍♂️.

It's Okay let's go for an analogy tour. Let's use [flash](https://www.dccomics.com/characters/the-flash) from DC Comics. If anyone not familiar with "flash". He's speedster, nerd, moron, who got superpower from lighting. Not only that it makes him run like thunder.
`If you think that you don't get it. Just see the intro of any episode. Same blah blah blah for every episodes😒😒😒`
[The Flash Series | Intro](https://youtu.be/Mx7xTF8fKz4)
![Troll Flash](https://media.giphy.com/media/ygBDQatBsywQmoGzS0/giphy-downsized.gif)

There's an episode in flash which very opt for this article. But I don't wanna stack you with these sci-fi stuffs. So, Imagine flash running on a Athlete track with his lighting speed⚡
![Athlete Track](https://cdn.pixabay.com/photo/2015/11/02/15/35/running-1018587_1280.png)

According to flash he see stuffs too slow which is completely opposite for us. So, I let's make him to do some stuffs.
For example: I want him to capture photo of 734th seat in the stadium and also I want him to change lane for every time he take photo of 734th seat in the stadium.
![So much math](https://media.giphy.com/media/5UCpmbzvZKQCfuF2P2/giphy.gif)

I don't want you to calculate. Just letting you know his capability⚡
This is event-loop. It runs on it's track by doing the tasks/process in the main thread.
![unbelievable](https://tenor.com/xvkk.gif)

# Main Thread?

`Don't worry this is not gist article. Trust me!`

In nature JavaScript is single-threaded i.e. it runs in single procress of CPU's bunch of processes. Process are called thread. Because it's good to have a convention which stick tight to the processor POV. Each core are compatible for certain limit of threads and virtualization, etc,. that's processor side which we don't really need here.

The thing is simple. The app you're running which is built in javascript runs only in one thread. That thread is known as `main thread` and that's where event-loop a.k.a `flash now runs😅 just joking!`. But here's the nolan twist for you 🤗. Well it's not totally true.
![deal with it](https://media1.tenor.com/images/6fe598c17fbe699654128ed3d5388d3f/tenor.gif)

Well the main purpose of the eventloop is to stick with main thread. So, whenever you pass a task which need more time to process. Then the eventloop will mark it and sends it to the engine i.e. [JavaScript Engine](https://en.wikipedia.org/wiki/JavaScript_engine). The engine runs the process and let the eventloop know when it's done. Then eventloop get the finished process from engine and do it's stuffs.

If you still struggling to wrap your head around?
Okay, I told you above, That there's an episode in flash which is very opt right! 
watch the below youtube video.

{% youtube GwolEq2pmoE %}

See! The main thread a.k.a is not protaganist anyway😂.
`just kidding. he is. Then why do we need a thread like 'savitar' anyways right?`

Well It turns out. We need it. because nowadays I don't wait to see the above video loading for even a second. I need that blazing fast performance✨ out of everything. because CPU's gettings shrink to 2nm & even smaller (`Anyway it don't know what is corona! I need to declare that 🤷‍♀️`)
![moron](https://media.giphy.com/media/t2eBr71ACeDC0/giphy.gif)

So, Threads will take care of that heavy lifting. Event-loop will let the Engine know about the process and engine creates or use another thread(`like Poor Savitar😅`) then join it to the main thread.

# But Actually how this works in JavaScript?

JavaScript has three concepts that we need to know first.

- Promises
- callback
- async await

Here's an free token to get out this article. You can either watch the below youtube videos to getting professional level knowledge(`see it in order`) or if you're good with me then trust I'll save you 🤗

- [Jake Archibald's Talk](https://youtu.be/cCOL7MC4Pl0)
- [Understanding JavaScript Promises in Simple English](https://www.youtube.com/watch?v=YiYtwbnPfkY&t=637s)
- [The Async Await Episode I Promised](https://www.youtube.com/watch?v=vn3tm0quoqE&t=3s)
- [Callback function](https://www.freecodecamp.org/news/javascript-callback-functions-what-are-callbacks-in-js-and-how-to-use-them/)

# Back to article

If you're reading still. Thanks mate for trusting me🤧
![Thanks](https://media.giphy.com/media/IMDpHiz2oVAxW/giphy.gif)

# Promises

It's nothing but the promise your girlfriend/boyfriend made to you😂. Either It'll be fulfilled or rejected a.k.a fake promise🤣.

Yeah, It's true. let me show you.
```
const myLovePromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('foo');
}, 300);
});

myLovePromise
.then(handleResolvedA, handleRejectedA)
.then(handleResolvedB, handleRejectedB)
.then(handleResolvedC, handleRejectedC)
.catch(err => { console.log(err) });
```
Every promise will have two parameters. Using this we can attach many function/operations depending on a single promise. This process is called promise-chaining.

![Simple right](https://media.giphy.com/media/26BRNoQJ5bRcZS8Hm/giphy.gif)

# Callback
It's the cool feature I've ever seen. A Callback function is just function. But passed an argument. See 😃 it's freakin awesome right!

```
// normal function
function myDisplayer(some) {
  document.getElementById("demo").innerHTML = some;
}

// function which accepts a function as parameter: myCallback
function myCalculator(num1, num2, myCallback) {
  let sum = num1 + num2;
  myCallback(sum);
}

// Passing function as a parameter
myCalculator(5, 5, myDisplayer);
```

If you need a simple and sweet example. Take `setTimeout Function`. All need to do is to pass your operations in as function with the delay.

# Async Await
This is an syntatic sugar for promises. After using the above method for some time. You'll realise that you are just pouring code in a single block. Instead of adding more readability to the code. That's where async await come in to picture.

 - [Refer this tutorial](https://javascript.info/async-await)
 - [The Async Await Episode I Promised](https://www.youtube.com/watch?v=vn3tm0quoqE&t=13s)

![I tried](https://media.giphy.com/media/KSKvdT1YGCpUIonvSq/giphy-downsized.gif)

# Finally

As it turns out event-loop handle these three concepts efficiently by catagorize them as [Microtasks and Macrotasks](https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide/In_depth). Each are treated in each way. For an elaborated explanation use MDN Docs.

So, Eventloop in JavaScript is crucial when it comes to task management. In server-side with the help of  NodeJS, You can play with the eventloop to get a good picture out of it.

Hope I confused you most enough with my explanation. 
![IDC](https://media.giphy.com/media/IffwQuk0uYwOIJEpon/giphy-downsized.gif)

Some developers openly stated in many videos, articles that JavaScript confusable and non-sensicle language. 

But If you ask me! 🤷‍♀️
![thats what she said](https://media.giphy.com/media/KCeVzKxHlfVkDmkeYH/giphy.gif)

`Com'on mate, It's a friendly programming language.`