DEV Community

Cover image for Microtasks
Vidushi Agrawal
Vidushi Agrawal

Posted on

Microtasks

Event Loop is used to perform asynchronous function in JavaScript. Event Loop monitors message queue and the execution stack to make sure that the callback functions are executed just after the execution stack gets empty. The callback functions are divided into macro-tasks and micro-tasks.
We will see the execution of microtask in the blog.

How is microtask executed?

Event Loop has a task queue also called macro-task. Once the callback in the message queue starts executing, it executes one macro-task first. When the macro-task gets executed then it goes to execute the micro-task queue. During the execution of the micro-task queue, if any additional microtasks gets added to the end of the queue then it is also executed at that same execution. Once the micro-task gets empty, it starts executing the macro-task queue.

Problems with Micro-task

It might happen that the micro-task keep queuing more micro-tasks and get stuck in an infinite loop. Render is also blocked during the execution of the micro-task queue. So if infinite loop is created or execution of microtask is taking too long, then the page will become unresponsive.

To avoid this, JS limits the simultaneous number of micro-tasks execution to 1000. This means that after 1000 micro-tasks, it has to pick up a macro-task and after the execution get back to the micro-task queue.

Promise callbacks as Micro-task

Promise callbacks should be queued as micro-task. This is because if we queue promise callbacks as macro-tasks then it may lead to performance problems, as callback may be unnecessarily be delayed by task-related thing such as rendering. It also causes non-determinism due to interaction with other task sources, and can break interactions with APIs.

Conclusion

We discussed about the execution of micro-task and the merits and demerits related to it.

Top comments (0)