TIL Microtask Queue vs the Call Stack Queue
POSTED ON:
TAGS: advanced javascript
This is probably the best graphic I can find to explain this topic.
First, it's the Call Stack
.
Things get added to the Call Stack
to get executed.
When everything is done from the Call Stack
, the Event Loop finds some new tasks to go after.
We used to just call it 'The Event Queue'.
But with the introduction of promises and async, we needed something that takes a bit more priority.
So now, we have the Microtask Queue, and the Macrotask Queue.
1. Microtask Queue
Anything resolved with promises.
The Event Loop will check this place FIRST.
When a Promise resolves and calls its then()
, catch()
or finally()
, method, the function within the method gets added to the microtask queue! This means that the function within the then()
, catch()
or finally()
method isn’t executed immediately. It's added in the microtask queue for processing!
If you make a promise that keeps adding new microtasks queues, it can crash the browser.
In Node, you can "starve" the Macrotask Queue by always adding new microtasks. It'll keep executing the microtask queue, because new things keep getting added.
2. Macrotask Queue
Anything with callbacks.
- setTimeout
- setInterval
- setImmediate
The big example
If you had some Promises
, and a setTimeout
Callback that both fired at the same time...
Promises will always show up first.
Via
Will Sentance's course, Javascript, the hard parts: https://frontendmasters.com/courses/javascript-hard-parts-v2/
and
Microtasks and (Macro)tasks in Event Loop
Related TILs
Tagged: advanced