9. Message Queue and Event Loop
MOYED
Posted on January 23, 2022
Articles
- JavaScript Event Loop Explained — Anoop Raveendran 100%
- The JavaScript Event Loop: Explained — Erin Sweson-Healey 30%?
- Understanding JS: The Event Loop — Alexander Kondov 100%
- Understanding the JavaScript Event Loop — Ashish Gupta 100%
- The JavaScript Event Loop — Flavio Copes 100%
- How JavaScript works: Event loop — Alexander Zlatkov 100%
- Tasks, microtasks, queues and schedules — Jake Archibald 70% not getting mictrotask queue
- Visualising the JavaScript Event Loop with a Pizza Restaurant analogy — Priyansh Jain 100%
- JavaScript Visualized: Event Loop — Lydia Hallie 100%
Question
How is Javascript asynchronous and single-threaded in same time?
The answer is Javascript is single=threaded, but not quite asynchronous. Asynchronous tasks are handled by the environment around Javascript like browser for example. Browser contains Web APIs, Task queue, Microtask queue, and Event loop which handles asychronous tasks.
Event loop
Event loop is a running process that watches call stack & queues. If the call stack is empty, it takes first event in Task queue and pushes it to the call stack.
Tick represents an iteration that event loop executes.
Mictrotask Queue (Job Queue)
Most asynchronous callbacks like setTimeout
or setInterval
goes to Task queue when it is fired. However, in ES6, Mictrotask queue was introduced as a queue that stores callback from the Promise
object, MutationObserver
, and etc.
Main difference between Task queue vs Microtask Queue
Most importantly, Mictrotask queue has priority to Task queue.
Additonaly, Mictrotask queue continues to push its callback into call stack untill the Mictrotask queue is empty.
console.log('script start');
setTimeout(function () {
console.log('setTimeout');
}, 0);
Promise.resolve()
.then(function () {
console.log('promise1');
})
.then(function () {
console.log('promise2');
});
console.log('script end');
// script start - promise1 - promise2 - setTimeout - script end
Although setTImeout
function's callback is added to Task queue faster than Promise
object's callback, as event loop visits to microtask queue first, Promise
object's callback is pushed to call stack and executed first.
Another point is that promise1 and promise2 logged at one stream. In case of Task queue, event loop only pushes callback to call stack one at a time. However, as it's previously mentioned, mictrotask queue moves stored callbacks to call stack untill it's empty.
Posted on January 23, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.