When you call job()
, sequenceB()
is called, then sequenceC()
is called. When sequenceB()
runs setTimeout(_ => console.log(' Timeout at B'), 0);
will be pushed to the callback queue and Promise.resolve().then(_ => console.log(' Promise at B'));
will be pushed to the job queue. Then the execution starts for sequenceC()
. The same happens again, setTimeout(_ => console.log(' Timeout at C'), 0);
is pushed to the callback queue and Promise.resolve().then(_ => setTimeout(console.log(' Promise at C'), 1000));
is pushed to the job queue.
Now the event loop says hey, is the job/microtask empty? And it's not, so that code gets executed, which is the promise from the sequenceB()
function, then it checks the job queue again, and it finds the other promise.
The next time around, it looks and the job/microtask queue is empty so then it looks at the callback queue and there is your setTimeout callback, so that gets pushed to the call stack. Once that executes, the event looks again and sure enough there is another setTimeout callback there. This is again executed and the process repeats.
With that being said the output is:
// from the microtask queue
Promise at B
Promise at C
// from the callback queue
Timeout at B
Timeout at C