Sobes.tech
Senior

Explain the difference between microtasks and macrotasks in the Event Loop

sobes.tech AI

Answer from AI

In the JavaScript Event Loop, microtasks and macrotasks are distinguished by priority and timing of execution:

  • Macrotasks are tasks added to the event queue (for example, event handlers, setTimeout, setInterval, I/O operations). After the current call stack is executed, the Event Loop takes the next macrotask from the queue and executes it.

  • Microtasks are tasks with higher priority, executed immediately after the current macrotask and before the Event Loop proceeds to the next macrotask. Examples of microtasks include promises (Promise.then), process.nextTick in Node.js.

In summary: after executing a macrotask, the Event Loop processes all microtasks from the microtask queue before moving on to the next macrotask. This ensures a faster response to asynchronous operations related to promises.

Example:

console.log('script start');

setTimeout(() => console.log('setTimeout'), 0); // macrotask

Promise.resolve().then(() => console.log('promise1')); // microtask
Promise.resolve().then(() => console.log('promise2')); // microtask

console.log('script end');

The output will be:

script start
script end
promise1
promise2
setTimeout