Web Technology Basics
console.log('A');
setTimeout(() => console.log('B'), 0);
Promise.resolve().then(() => console.log('C'));
console.log('D');When the JavaScript above is run in a browser, which of the following is the order in which the characters are shown on the console?
- AA → B → C → D
- BA → D → B → C
- CA → D → C → B
Show answer and explanation
Answer: C. A → D → C → B
A page's JavaScript runs on a single main thread, and no other work cuts in until the currently running code finishes. First, all the synchronous code runs, showing A and D. The function passed to the Promise's then runs as a microtask immediately after the current code finishes, so C is shown next. Even with 0 ms given to setTimeout, its function is put into the queue as a task, and the event loop takes it out only after the microtasks are done, so B comes last.
- A. Functions passed to setTimeout or then are not run on the spot; they run after the synchronous code finishes.
- B. Promise callbacks (microtasks) run before setTimeout callbacks (tasks).
- C. Correct. The order is the synchronous A and D, then the microtask C, then the task B.