Micro- and macrotasks. Event loop.

Micro- and macrotasks. Event loop.

October 5, 2022 - 2 minutes read

JavaScript is a single-threaded language - which means that only one piece of code can be run at once. However, I'm sure that you have noticed that setTimeout, Promises, fetch, etc. don't block the UI and the user is still able to use it. You may wonder why and the answer is Event Loop.

In JavaScript, once a function invocation is seen, a new frame for it is created and added to Call Stack. Then all of them are executed from the latest one - the FILO (First In Last Out) rule.

code-callstack.png

Cool, so let's take a look at this code:

1console.log(1); 2setTimeout(() => console.log(2)); 3new Promise((res) => res()).then(() => console.log(3)); 4console.log(4); 5

Spend some time analyzing the code and try to figure out what's the output.

And the correct answer is ... 1, 4, 3, 2. If your answer was different - no worries I'll explain it in a minute. :)

So basically when you write code in JavaScript you use JS API like Math.random(), etc. but you can also (and you do!) use external APIs provided by your environment - a browser or node.js. The most popular ones are timers (setTimeout, setIntervals), DOM API (document.querySelector) or fetch. When you call them, the browser handles the execution in a separate thread. Then you have to pass e.g. callback that should be invoked once the function finishes. For instance, in the example above, when the setTimeout is met, the JS engine delegates the execution to the browser and moves to the next one.

Okay, I hope it's clear by now. However, probably you wondering now when the callback should be handled by the engine after the setTimeout finishes. So we need to introduce 3 new concepts:

  • Microtask - a task that is being executed once the callstack is empty and before the browser's planned work
  • Macrotask - a task that is being executed once the callstack and the microtaks queue are empty. It allows the browser to finish its planned work.
  • Event loop - it keeps an eye on the callstack and moves callbacks' frames from microtasks and macrotasks queues to the callstack for execution.

1_XVqPA2z1dTHJWm2TwIAsBw.gif

(credits: https://medium.com/@saravanaeswari22/microtasks-and-macro-tasks-in-event-loop-7b408b2949e0)

So as you can see in the visualization above, once the callstack is empty, event loop gets another item from the microtask queue and finally clears macrotasks queue.

Related Posts

Categories