Sitemap

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.

8 min read8 hours ago

--

Press enter or click to view image in full size

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
Timer

Why?

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…

--

--

Rothy Yorn
Rothy Yorn

Written by Rothy Yorn

Software engineer passionate about building, learning, and sharing insights about development, QA, automation, and technology.