# Event Loop
## Prequel
Before we can start talking about Event Loop, there ware some concepts we should talk first:
1. interpreted vs compiled language
3. concurrency
### Interpreted vs compiled language
A compiled langue is a programming language that will be converted by some program (a compiler) to a binary file, and whenever this binary file is executed the code will run. Think of a binary file as the most raw possible format of commands executed by your computer, (like 0s and 1s).
An interpreted language in another hand is never converted to a binary executable file. An interpreted code is a type of code that will be processed by another kind of code (normally referred to a lower level code) and instead of creating some binary file that will be executed it executes the code directly.
In another words: interepreted languages are languages that will be interpreted by some other language, like the name suggests (duuuh)

#### JS is an interpreted language
So, JS is an interpreted language, mostly being intepreted by a C++ interpreter (in modern browsers at least), what does that mean exactly?
That means that every single thing you see running on a JS code is actually not running in JS, it's running on a C++ code that interprets that JS code!
So for example:

```html
<html lang="en">
<body>
<button id="button">button</button>
<script>
const button = document.getElementById("button");
button.onclick = () => {
doSomething()
}
</script>
</body>
</html>
```
Let's assume there's a `button` somewhere in your screen and an event listener to the button click is added through JS code.
What's actually happening is some C++ code is running in the background and everytime you click that button, this C++ code is going to ensure that all listeners you added through JS is invoked when you click that button! In fact, the button itself is also produced by C++ code ๐ฑ
That ``"some C++ code"`` running is commonly referred to as the `Event Loop` and it looks somewhat (in a rather simplified way....) like this:
```cpp
while (queue.waitForMessage()) {
queue.processNextMessage();
}
```
### Concurrency
#### What is Concurrency?
> Concurrent computing is a form of computing in which several computations are executed concurrently โ during overlapping time periods โ instead of sequentially โ with one completing before the next starts.
#### What is Parallelism?
> Parallel computing is a type of computation in which many calculations or processes are carried out simultaneously. Large problems can often be divided into smaller ones, which can then be solved at the same time
#### What is the difference?

The difference is the amount of Threads involved in the computation model. Concurrency refers to multiple process competing with each other in a same thread, meanwhile prallelism indicates a multiple thread scenario where each process can be executed indepedently in a single thread.
#### What the #$%^ is a thread ๐ชก๐งต?
TLDR; A thread is a piece of code that can be executed separately, providing the possibility of running multiple process at the same time!
Have you ever heard about your computer having multiple CPUs?! that's intertwined with the idea of threads, since threads can be executed simultanesouly, each one of them can execute in a different CPU!
#### What about JS?!
Strictly speaking about the browser, JS is an concurrent language. Meaning everything will run in a single thread and process units will race against each other and also run against browser specific tasks!!! like CSS layout, animations and painting.
Which means we can get some really nasty things to happen, for example:
```js
while(true);
```
What do you think it'll happen if we press this `while (true);` button?
http://event-loop-tests.glitch.me/while-true-test.html
<iframe src="http://event-loop-tests.glitch.me/while-true-test.html" width="100%" height="300" frameBorder="0"></iframe>
Yeah... since all JS code is concurrent and we're running an `infinite loop` it means that that code will simply stop the execution on your whole web page, meaning css will stop working, animations will stop working, text selection will stop working, clicks will stop working.... EVERYTHING will stop working! ๐ฑ
<iframe src="https://giphy.com/embed/QMHoU66sBXqqLqYvGO" width="100%" height="300" frameBorder="0"></iframe>
### Conclusions
1. interpreted vs compiled language
* JS is an interpreted language, by the end of the day, every JS code is actually being executed by a C++ interpreter
3. concurrency vs parallelism
* JS is a concurrent languague, there is no parallelism (*)
* JS is single threaded (*)
## Main
Ok, now that we went through all the info we should know beforehand, it's time for the real deal.
### why in gods name do I need to know about Event loop?
Well, honestly... it's considered an advanced topic and I totaly agree might be too much ๐, here are some things I put on the bucket list of why you should at least try to understand it:
1. JS runs on it! It's how your code will run!
yeah... there's only one item on the list.... it should be enough ๐
### What is the Event Loop?
<iframe width="560" height="315" src="https://www.youtube.com/embed/cCOL7MC4Pl0?start=821" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
As we stated at [JS is an interpreted language](#js-is-an-interpreted-language), the event loop got its name because of how it's usually implemented, which usually resembles:
```cpp
while (queue.waitForMessage()) {
queue.processNextMessage();
}
```
`queue.waitForMessage()` waits synchronously for a message to arrive (if one is not already available and waiting to be handled). while `queue.processNextMessage()` will execute all required code to process the next message in the queue.
#### Adding messages
In web browsers, messages are added anytime an event occurs and there is an event listener attached to it. If there is no listener, the event is lost. So a click on an element with a click event handler will add a message โ likewise with any other event.

##### Another way to add tasks (messages)
Besides DOM events firing messages in the Event Loop, some methods also have this ability:
1. `setTimeout`, `setInterval` & `setImmediate`
2. `requestAnimationFrame`
3. `Promises` and therefore `fetch`
4. `postMessage`
5. `queueMicrotask`
6. `Observers`
A message added to the Event Loop queue is also known as either a `Task` or a `Micro Task`.
#### Call stack
The call stack, as the name suggests it's a stack!

A stack of all methods to be executed during a message processing on the Event Loop, everything that goes throuhg the event loop ends up generating process on the call stack.
Take this code for example:

[Let's visualize that a bit](https://www.jsv9000.app/?code=ZnVuY3Rpb24gY291bnREb3duKG4pIHsKICAgIGlmIChuIDw9IDApIHsKICAgICAgICByZXR1cm4KICAgIH0KICAgIGNvbnNvbGUubG9nKG4pCiAgICBjb3VudERvd24obiAtIDEpCn0KCmNvdW50RG93big1KQ%3D%3D):
```js
function countDown(n: number) {
if (n <= 0) {
return
}
console.log(n)
countDown(n - 1)
}
```
### How does the Event Loop works?
Well, as stated before:
```cpp
while (queue.waitForMessage()) {
queue.processNextMessage();
}
```
Event loop works by waiting for messages (`Tasks` or `Micro tasks`), and then processing them! The processing of a message occurs by the execution of all the JS code required by that message on the `Call Stack`

A more precise pseudo JS code of the Event loop would be like this:
```javascript
while (queue.waitNextMessage()) {
const taskQueue = queue.taskQueue;
// if there is a task in the queue, than process that task
if (taskQueue.hasNextTask()) {
taskQueue.processNextTask();
}
const microtaskQueue = queue.microTaskQueue;
// while there are micro tasks, proccess them all
while (microtaskQueue.hasNextMicrotask()) {
microtaskQueue.processNextMicrotask();
}
// re-render the UI, all CSS recalculation, animations
// and any visual effects goes here!
rerender();
}
```
### Examples
#### Blink the box
<iframe src="https://codesandbox.io/embed/broken-https-urs1uh?fontsize=14&hidenavigation=1&theme=dark"
style="width:100%; height:500px; border:0; border-radius: 4px; overflow:hidden;"
title="broken-https-urs1uh"
allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
></iframe>
#### Moving the box
<iframe src="https://codesandbox.io/embed/vigilant-estrela-u3f4sd?fontsize=14&hidenavigation=1&theme=dark"
style="width:100%; height:500px; border:0; border-radius: 4px; overflow:hidden;"
title="vigilant-estrela-u3f4sd"
allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
></iframe>
# Resources
https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop