Answer would be Option 3 i.e. 1 7 3 5 2 6 4.

Let us understand why:

  1. console.log(1) executes immediately and it outputs 1.
  2. setTimeout(() => console.log(2)); schedules a callback to the macrotask queue.
  3. Promise.resolve().then(() => console.log(3)); schedules a callback to the microtask queue.
  4. Promise.resolve().then(() => setTimeout(() => console.log(4))); schedules a callback to the microtask queue.
  5. Promise.resolve().then(() => console.log(5)); schedules a callback to the microtask queue.
  6. setTimeout(() => console.log(6)); schedules a callback to the macrotask queue.
  7. console.log(7); executes immediately and it outputs 7.

So far, we have 1 7 as output. Now,

Since microtasks takes precedence over macrotasks.

The callback scheduled via line no. 3 (console.log(3);) executes and is printed to console.

  • Output so far: 1 7 3

The callback scheduled via line no. 4 executes and sets a new macrotasks as setTimeout callbacks are added macrotasks queue.

The callback schedules via line no. 5 executes and is printed to console.

  • Output so far 1 7 3 5

Now, comes the turn of macrotasks as all the microtasks are over.

The callback scheduled via line no. 2, 6, 4 are executed in order and printed to console.

Final output 1 7 3 5 2 6 4

To develop a deeper understanding of the Promises, Event Loop, Macrotasks/Microtasks queues, checkout

https://devtools.tech/resources/s/javascript-promises-fundamentals-every-engineer-should-know-or-part-2-or-event-loop-or-microtasks---rid---oBrzK6Mt7HNAnKBT3ogC

https://devtools.tech/resources/s/things-every-engineer-should-know-about-promises-in-javascript-or-frontend-fundamentals---rid---CpzShsPEajyOwTavUu5O