Asynchronous JavaScript — Part 3 of 4
Wait! There are two queues?
In my previous post, ChatGPT mentioned that promises resolve from the event loop. This is true but deceiving.
Promises aren’t placed in the event queue; instead, they go to the microtask queue. The key difference? The microtask queue takes priority over the event queue, which can block the main thread. In practical terms, microtasks can be DOM blocking!
It’s also worth noting that promises by themselves aren’t fully asynchronous. If you want to delay execution and push a task to the event queue, you need to use something like setTimeout. This is why you’ll see senior engineers use setTimeout with a delay of 0. IMO, this is the main way to use setTimeout — though there are always exceptions.
When buttons are clicked on a website, is that sent to the microtask queue or the event queue? Why?
Next: Asynchronous JavaScript — Part 4 of 4
Prev: Asynchronous JavaScript — Part 2 of 4