Sobes.tech
Middle+

Tell about Event Loop: in what order are synchronous code, microtasks, and macrotasks executed?

sobes.tech AI

Answer from AI

Event Loop is a mechanism in JavaScript that manages the execution of code, event handling, and asynchronous operations.

Order of execution:

  1. Synchronous code executes immediately, in order, on the main thread.
  2. After synchronous code executes, microtasks (microtasks) are run. Microtasks include, for example, promises (Promise.then), process.nextTick in Node.js.
  3. Then, macrotasks (macrotasks) are executed, such as event handlers, timers (setTimeout, setInterval), network requests.

The cycle repeats: after each macrotask, the Event Loop checks the microtask queue and executes all microtasks before moving on to the next macrotask.

Example:

console.log('Synchronous code');

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

Promise.resolve().then(() => console.log('Microtask (Promise)'));

console.log('Synchronous code 2');

The output will be:

Synchronous code
Synchronous code 2
Microtask (Promise)
Macrotask (setTimeout)

This demonstrates that microtasks are executed immediately after synchronous code, but before macrotasks.

Tell about Event Loop: in what order are synchronous… - sobes.tech