Join waitlist
JavaScriptCommunity question

setTimeout 0 runs after promise.then?

Asked by Sneha Reddy 1 month ago 3 answers 11 votes
console.log('A');
setTimeout(() => console.log('B'), 0);
Promise.resolve().then(() => console.log('C'));
console.log('D');

I said A D B C, answer is A D C B. why does the promise go before a 0ms timeout

3 answers

Arjun Mehta1 month agoMost voted10

Promise callbacks go to the microtask queue, setTimeout goes to the task (macrotask) queue. After the current script finishes, the event loop runs all microtasks first, then one task.

So A, D (sync), C (microtask), B (task). 0ms just means "not before 0ms", not "right now".

aman khan1 month ago2

harder version: setTimeout inside a then and a then inside a setTimeout. same rule, just go step by step

Riya Banerjee1 month ago2

this exact question came in my Juspay interview 🥲

Related questions

Go deeper

Want the full explanation, not just an answer?

Structured lessons on DSA, core CS, Java and interview skills, each ending in a quiz so you know it stuck.