Concurrency & Workers

Preview — 3 of 10 questions

What is the correct execution order of the following code?

javascript
console.log('Start');

setTimeout(() => {
  console.log('Macrotask 1');
  Promise.resolve().then(() => console.log('Microtask 1'));
}, 0);

Promise.resolve().then(() => {
  console.log('Microtask 2');
  return Promise.resolve().then(() => console.log('Microtask 3'));
});

setTimeout(() => {
  console.log('Macrotask 2');
  Promise.resolve().then(() => console.log('Microtask 4'));
}, 0);

console.log('End');
AStart → End → Microtask 2 → Microtask 3 → Macrotask 1 → Microtask 1 → Macrotask 2 → Microtask 4
BStart → End → Macrotask 1 → Microtask 1 → Microtask 2 → Microtask 3 → Macrotask 2 → Microtask 4
CStart → End → Microtask 2 → Macrotask 1 → Microtask 1 → Microtask 3 → Macrotask 2 → Microtask 4
DStart → End → Macrotask 1 → Macrotask 2 → Microtask 2 → Microtask 3 → Microtask 1 → Microtask 4

What will the following code output and why?

javascript
console.log('Before');

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

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

console.log('After');
ABefore → After → Inside Promise → Inside Timeout 1 → Inside Timeout 2
BBefore → After → Inside Timeout 1 → Inside Promise → Inside Timeout 2
CBefore → Inside Timeout 1 → After → Inside Promise → Inside Timeout 2
DBefore → Inside Promise → After → Inside Timeout 1 → Inside Timeout 2

Which of the following statements about the following code is correct?

javascript
setTimeout(() => {
  console.log('Timeout 1');
  setTimeout(() => {
    console.log('Timeout 2');
    Promise.resolve().then(() => {
      console.log('Promise in Timeout 2');
    });
  }, 0);
}, 0);

Promise.resolve().then(() => {
  console.log('Promise 1');
  setTimeout(() => {
    console.log('Timeout 3');
  }, 0);
});

console.log('Synchronous Code');
ASynchronous Code → Promise 1 → Timeout 1 → Timeout 2 → Promise in Timeout 2 → Timeout 3
BSynchronous Code → Promise 1 → Timeout 1 → Promise in Timeout 2 → Timeout 2 → Timeout 3
CSynchronous Code → Timeout 1 → Timeout 2 → Promise 1 → Promise in Timeout 2 → Timeout 3
DSynchronous Code → Timeout 1 → Promise 1 → Timeout 2 → Promise in Timeout 2 → Timeout 3

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.