In JavaScript, tasks are queued and executed by the event loop. These tasks are divided into two categories: microtasks and macrotasks.
Microtasks are tasks that are executed at the end of the current event loop iteration, before the next macrotask is executed. Microtasks are usually higher priority tasks that need to be executed as soon as possible. Examples of microtasks include promise callbacks, mutation observers, and queueMicrotask().
Macrotasks, on the other hand, are tasks that are queued in the event loop and executed after all microtasks have been executed. Macrotasks are usually lower priority tasks that can be delayed without affecting the user experience. Examples of macrotasks include setTimeout(), setInterval(), and requestAnimationFrame().
Here’s an example to illustrate the difference between microtasks and macrotasks:
console.log('1');
setTimeout(() => {
console.log('2');
}, 0);
Promise.resolve().then(() => {
console.log('3');
});
console.log('4');
In this example, the code is executed in the following order:
The console logs "1". A setTimeout() function is called with a callback function that logs "2". The timer is added to the macrotask queue. A promise is resolved with a callback function that logs "3". The callback function is added to the microtask queue. The console logs "4".
After the initial execution, the event loop starts processing the microtask queue, and the callback function for the promise is executed, logging "3". Then, the event loop moves to the macrotask queue and executes the callback function for the setTimeout() function, logging "2".
So, in summary, microtasks have higher priority than macrotasks and are executed before the next macrotask is executed. Understanding the difference between microtasks and macrotasks is important for writing efficient and responsive JavaScript code.