DEV Community

Pulkit Kashyap
Pulkit Kashyap

Posted on

Understanding Microtasks and tasks in JS

Well, as Javascript developers we all are in a habit of using promises, timers etc. Whenever we think of making a particular piece of code asynchronous the first thing that comes to our mind is using promises or maybe a setTimeout(). Have you ever wondered how these things work under the hood? I have been going through a lot of blogs regarding execution queues, microtasks and tasks, so I decided to jot down my learnings in this post.

Let's start off with a quick exercise(just to brush up your javascript skills)

Now put on your thinking hats and think what output of above code snippet would be.

The correct answer goes as

  1. call the printer
  2. Inside the Printer
  3. Promise resolved
  4. Timeout 1

Yes the output is not exactly what a lot of us must be expecting🤷‍♂️ 🤷‍♂️. But what goes on behind the scenes in Javascript is very engaging.

Actually when the printer function is called the Inside the Printer is logged. Now the important thing to note here is that even when the timer is set to 0 the log statement inside setTimeout() is executed after promise is resolved. To understand this you need to know how the event loop handles tasks and microtasks. The event loop runs continuously and ensures that all the tasks queued are executed sequentially. So in our case the setTimeout() is scheduled as a task which is executed in the next event loop. But the question here remains is How the hell does Promise log the statement first?

Promises are queued as microtasks. Microtasks are executed straight after the currently executing script and thus promises are resolved in the same event loop. Calling .then() puts the promise in the microtask queue. The microtask queue is processed after callbacks as long as no other JavaScript is mid-execution. That is why Promise resolved is logged before Timeout 1.

The crux is -:

  • Tasks have to wait for next round of execution
  • Microtasks can execute in the same round after the current script finishes execution

Hopefully I could explain the topic in a simple yet effective manner. Bye !!!

Top comments (3)

Collapse
 
somedood profile image
Basti Ortiz

Well, that was more straightforward than I first expected. For further reading to those interested, here's a great talk about the JavaScript event loop:

Collapse
 
mebble profile image
Neil Syiemlieh

This other talk provides more detail on microtasks and works great as a continuation of that one

Collapse
 
anduser96 profile image
Andrei Gatej

This article made things clear for me as well!