Sobes.tech
Middle

What is the difference between setTimeout and await promise in terms of microtasks and macrotasks in the event loop?

sobes.tech AI

Answer from AI

setTimeout and await promise work with different queues in the event loop.

  • setTimeout places the callback in the macrotask queue. This means that after the current call stack and all microtasks are completed, the event loop will process the macrotasks and execute the callback from setTimeout.

  • await promise (or .then) places the continuation in the microtask queue. Microtasks are executed immediately after the current call stack and before macrotasks.

Summary:

  1. The current code executes first.
  2. Then all microtasks (promise continuations, await) are executed.
  3. After that — macrotasks (setTimeout, events, etc.).

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

This shows that microtasks (promises) are executed before macrotasks (setTimeout).

What is the difference between setTimeout and await… - sobes.tech