Event Loop
Overview

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.
function multiply(x, y) {
return x * y;
}
function printSquare(x) {
var s = multiply(x, x);
console.log(s);
}
printSquare(5);
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 ,
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 queueFor 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
Last updated
Was this helpful?