Ever noticed this in JavaScript? 👀
--------
console.log("start");
setTimeout(() => console.log("timeout"));
Promise.resolve().then(() => console.log("promise"));
console.log("end");
--------
Most developers expect setTimeout to run first.
But the output is:
--------
start
end
promise
timeout
--------
Why?
Because Promises go into the Microtask Queue, while setTimeout goes into the Macrotask Queue.
The JavaScript event loop always processes all microtasks before the next macrotask once the call stack is empty.
Execution order becomes:
1️⃣ Synchronous code
2️⃣ Microtasks (Promise, queueMicrotask)
3️⃣ Macrotasks (setTimeout, setInterval, DOM events)
So even setTimeout(fn, 0) will run after Promise callbacks.
Understanding this small detail helps explain many tricky async bugs in real applications.
#javascript #webdevelopment #frontend #async #eventloop
Me: three values. JavaScript Set: I see ONE. Result → 1 🤯