Member-only story
JavaScript Microtasks vs Tasks: Why Promises Run Before setTimeout
Understand the JavaScript event loop, why Promise callbacks run before timers, and how an endless chain of microtasks can make a browser unresponsive.
You write two asynchronous operations in JavaScript:
setTimeout(() => console.log("Timer"), 0);Promise.resolve().then(() => console.log("Promise"));You might expect the timer to run first because its delay is zero.
But the output is:
Promise
TimerWhy?
The answer is one of the most important concepts in JavaScript: the event loop.
JavaScript does not execute every callback as soon as it becomes ready. It uses different scheduling mechanisms to decide when callbacks can run. Two particularly important categories are tasks and microtasks.
Promise callbacks use the microtask queue. Timer callbacks use a task queue. After the current synchronous JavaScript finishes, the runtime processes pending microtasks before moving on to another task.
This scheduling behavior explains more than a simple console output. It affects asynchronous…










