Sobes.tech
Middle+

Tell us about asynchronous JavaScript: microtask and macrotask queues, how does the Event Loop work?

sobes.tech AI

Answer from AI

In JavaScript, asynchrony is implemented through the Event Loop, which manages the execution of code, events, and asynchronous operations.

Macrotasks (task queue) — these are queues of tasks such as event handlers, setTimeout, setInterval, network requests. After the current call stack is executed, the Event Loop takes the next macrotask from the queue and executes it.

Microtasks (microtask queue) — these are queues of higher-priority tasks, such as promises (Promise.then/catch/finally), MutationObserver. After each macrotask, the Event Loop first executes all microtasks in the queue before moving on to the next macrotask.

How the Event Loop works:

  1. The call stack (synchronous code) is executed.
  2. When the stack is empty, the Event Loop takes all microtasks from the queue and executes them in order.
  3. After executing microtasks, the Event Loop takes one macrotask from the queue and executes it.
  4. The cycle repeats.

This ensures that microtasks are executed before the next macrotask, which is important for the sequence of asynchronous operations.

Example:

console.log('start');
setTimeout(() => console.log('timeout'), 0);
Promise.resolve().then(() => console.log('promise'));
console.log('end');

The output will be:

start
end
promise
timeout

Because the promise (microtask) executes after the synchronous code but before the setTimeout macrotask.