JavaScript Async Execution Order

🚨 JavaScript Async Interview Question What will be the output? console.log("Start"); setTimeout(() => { console.log("Timeout 1"); }, 0); Promise.resolve() .then(() => { console.log("Promise 1"); }) .then(() => { console.log("Promise 2"); }); setTimeout(() => { console.log("Timeout 2"); }, 0); console.log("End"); Looks simple… But many developers get the order wrong. Because JavaScript doesn’t execute async code the way we intuitively expect. This question tests your understanding of: • Call Stack • Microtask Queue • Macrotask Queue • JavaScript Event Loop What do you think the output will be? #JavaScript #FrontendInterview #EventLoop #ReactJS #FrontendDeveloper #ProductBasedCompany

Small hint for anyone trying to solve this: Think about the order of execution between synchronous code → microtasks (Promises) → macrotasks (setTimeout).

JavaScript runs synchronously on a single thread via the Call Stack. When async tasks appear, the Event Loop manages them in this order once the call stack is empty: Microtasks — Promises, async/await (all drained first) Macrotasks — setTimeout, setInterval (one at a time)

Start End Promise 1 Promise 2 Timeout 1 Timeout 2

output will be Start End Promise 1 Promise 2 Timeout 1 Timeout 2because promises go in Microtasks and it as higher prority

This question also tells us about the priority given by event loop.

Start End Promise 1 Promise 2 Timeout 1 Timeout 2

Output : Start End Promise 1 Promise 2 Timeout 1 Timeout 2 Reason: Call stack: Executes synchronous code immediately Microtask Queue: Promises callbacks (then, catch, finally) Macrotask Queue: setTimeout, setInterval, etc. Priority order: 1.call stack (synchronous code) 2.microtask queue (promises) 3.Macrotask queue (setTimeout)

Like
Reply

Good question. Understanding the JavaScript event loop and microtasks is essential for async programming.

Like
Reply

start end promise 1 promise 2 Timeout 1 Timeout 2, Microtasks run before macrotask.

Like
Reply

Start, end, promise 1, promise 2, Timeout 1 and Timeout 2. Start and end executes first because it is main(), Promises comes the second and setTimeout comes the least priority!

Like
Reply
See more comments

To view or add a comment, sign in

Explore content categories