function job(){
sequenceB()
sequenceC()
}
function sequenceB(){
setTimeout(_ => console.log(`š
Timeout at B`), 0);
Promise.resolve().then(_ => console.log('š Promise at B'));
}
function sequenceC(){
setTimeout(_ => console.log(`š
Timeout at C`), 0);
Promise.resolve().then(_ => setTimeout(console.log('š Promise at C'), 1000));
}
job();
what will be the print order here and why? I seem to get the output in this order š Promise at B, š Promise at C, š Timeout at B, š Timeout at C
tested this on both chrome(latest version) and edge(latest version)
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