# Event Loop

## Overview

<figure><img src="https://1374779285-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFW3x2aqEO8GF2kr3VU%2Fuploads%2Fs2qjJcJWH5H6FlXqpacF%2Fimage.png?alt=media&#x26;token=87d53ff6-8633-4602-848e-f848f1e92610" alt=""><figcaption></figcaption></figure>

* JavaScript Run time consists of several components which allows code to execute in a non-blocking way

## Stack

* If we step into a function, we put it on the top of the stack. If we return from a function, we pop off the top of the stack. That’s all the stack can do.

```javascript
function multiply(x, y) {
    return x * y;
}
function printSquare(x) {
    var s = multiply(x, x);
    console.log(s);
}
printSquare(5);
```

![](https://1374779285-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFW3x2aqEO8GF2kr3VU%2Fuploads%2FOuMeOzwgFtLn9CfXZYb0%2Fimage.png?alt=media\&token=5873f5e6-7bb5-412a-92a4-9bdd6d12f6fb)

## Heap

* Objects are allocated in a heap which is just a name to denote a large (mostly unstructured) region of memory.

## Queue

* The message queue (micro task queue,  task queue) that store the list of callback function ,&#x20;

```javascript
setTimeout(()=>{
    console.log(1);
},0);

Promise.resolve(2).then((data)=>{console.log(data);});

console.log(3);

// Output: 3 2 1
```

* After executing time out and resolved promise, the callback function is put into queue
* For web api call back function , such as `setTimeout` , the callback will be saved into task queue
* For promise callback function, it will be saved into micro task -queue
* Micro task queue has higher priority, so promise resolve go first :)

## Event loop

* It is used listen to the call stack whether it is empty or not
* When call stack is empty, it will push the callback function in the queue into it

## Reference

{% embed url="https://blog.sessionstack.com/how-javascript-works-event-loop-and-the-rise-of-async-programming-5-ways-to-better-coding-with-2f077c4438b5" %}

{% embed url="https://www.youtube.com/watch?v=eiC58R16hb8" %}
