Challenge 3 — Solution Task: Write code with TWO setTimeout calls (both 0ms, logging "timeout A" and "timeout B" in that order) and ONE promise .then() (logging "promise") scheduled between them. Run it and explain in a comment why the promise callback runs before EITHER timeout, despite being scheduled in the middle. setTimeout(() => console.log("timeout A"), 0); Promise.resolve().then(() => console.log("promise")); setTimeout(() => console.log("timeout B"), 0); // Output: // promise // timeout A // timeout B // // Explanation: setTimeout always schedules a MACROTASK, while // Promise.resolve().then() schedules a MICROTASK. Regardless of the // order they were written in the code, JavaScript fully empties the // microtask queue before running even the FIRST macrotask that's // waiting. So "promise" runs before "timeout A", even though // "timeout A" was scheduled earlier in the source code. // // Once the microtask queue is empty, the two macrotasks then run in // the order they were scheduled relative to EACH OTHER — "timeout A" // before "timeout B" — since both have the same 0ms delay and // macrotasks of equal priority run in scheduling order. Notes: - This combines the two earlier challenges' lessons into one example: microtasks beat macrotasks regardless of write order, and macrotasks among themselves still respect their own scheduling order. - If a second .then() were added after "timeout B"'s setTimeout call, it would still run before BOTH timeouts, for the exact same reason — the microtask queue is drained completely before the event loop even looks at the macrotask queue. - This is precisely why production code shouldn't assume setTimeout callbacks and promise callbacks interleave in the order they appear on the page.