October 23rd, 2019
If we have two asynchronous tasks that complete immediately then in which order will they complete in? This will depend on the order they were created in and also whether they are Micro or Macro tasks. Micro tasks such as those created by promises will be executed immediatley after your code completes and before the event loop will action any other pending tasks Macro tasks such as setTimout are simply placed onto the task queue to be picked by the event loop. So they may occur after a render or any other task that is already sitting on the queue.
In this case all things being equal we might think that the Timeout Task would complete first as it was created first.
But as the Timeout task is in fact a Macro task it will be queued up and run when the browser is all good and ready. This could potentially be seconds if the browser is stuck with an intensive task or has lots of tasks already queued up and ready to go. The event loop will process these pending tasks including ours in a First in First Out (FIFO) order and we'll just have to wait our turn.
The Promise however is a Micro task and as such will be executed immediately and the end of the code block. The browser won't get a chance to sneak any of its pending tasks in beforehand here!
So when is it useful to know this.. one scenario is that of needing to split up a long task into chunks and ensure that the screen is refreshed in between each chunk of work. This can be useful for say displaying the progress of long running task. In this case we'd need to ensure that we use a Macro Task like setTimeout rather than a Micro Task.
For more information on the Event Loop I've placed a link to a talk by Jake Archibald which is an excellent overview.
The Event Loop (Jake Archibald)
And also for a video going through the above in codepen see below:
https://www.youtube.com/watch?v=Rpb-hZjw--w
Hope this was useful!