Sobes.tech
Middle

Look at the code with console.log, setTimeout, and Promise and explain in what sequence what will be output.

sobes.tech AI

Answer from AI

Let's consider an example with console.log, setTimeout, and Promise:

console.log('Start');

setTimeout(() => {
  console.log('Timeout');
}, 0);

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

console.log('End');

The output sequence will be:

  1. Start — synchronous call.
  2. End — synchronous call.
  3. Promise — a microtask, executed after the current call stack but before macrotasks.
  4. Timeout — a macrotask, executed after microtasks.

This is because JavaScript first executes all synchronous code, then microtasks (Promises), and only then macrotasks (setTimeout).

Thus, the output will be:

Start
End
Promise
Timeout

If your question contains different code, the principle remains the same: synchronous code —> microtasks (Promise) —> macrotasks (setTimeout).