Sobes.tech
Middle

setTimeout(function timeout() { console.log('Timeout'); }, 0); let p = new Promise(function(resolve, reject) { console.log('Creating promise'); resolve(); }); p.then(function(){ console.log('Processing promise'); }); console.log('End of script'); // Complex case // console.log(1); // setTimeout(() => console.log(2)); // Promise.resolve().then(() => console.log(3)); // Promise.resolve().then(() => setTimeout(() => console.log(4))); // Promise.resolve().then(() => console.log(5)); // setTimeout(() => console.log(6));

sobes.tech AI

Answer from AI

Let's analyze the order of output in this code:

setTimeout(function timeout() {
  console.log('Timeout');
}, 0);

let p = new Promise(function(resolve, reject) {
  console.log('Creating promise');
  resolve();
});

p.then(function(){
  console.log('Promise handling');
});

console.log('End of script');
  1. First, all synchronous code executes:

    • setTimeout sets a timer with 0 delay (asynchronously).
    • A promise is created, and "Creating promise" is immediately logged.
    • The promise is immediately resolved.
    • A .then handler is registered (placed in the microtask queue).
    • "End of script" is logged.
  2. After synchronous code execution, microtasks (promise handlers) are executed:

    • "Promise handling" is logged.
  3. Then, macrotasks (timers) are executed:

    • "Timeout" is logged.

Final output order:

Creating promise
End of script
Promise handling
Timeout

Complex case with comments:

console.log(1);

setTimeout(() => console.log(2));

Promise.resolve().then(() => console.log(3));

Promise.resolve().then(() => setTimeout(() => console.log(4)));

Promise.resolve().then(() => console.log(5));

setTimeout(() => console.log(6));

Explanation:

  • First, console.log(1) runs synchronously.
  • Then, timers are set for 2 and 6 (macrotasks).
  • Promise handlers (microtasks) log 3, set a timer for 4, and log 5.

Execution order:

  1. 1 — synchronous
  2. Microtasks:
    • 3
    • 5
    • the second microtask sets a timer for 4
  3. Macrotasks:
    • 2
    • 6
    • 4 (after the timer is executed)

Final output:

1
3
5
2
6
4

This demonstrates that microtasks execute immediately after synchronous code, while macrotasks execute after microtasks, even if timers have zero delay.