Why setTimeout Cannot Be Trusted
setTimeout(fn, 5000) does not guarantee 5 seconds. It guarantees at least 5 seconds. If the stack is busy, it could be much longer.
The delay is a minimum, not a guarantee. setTimeout(fn, 0) still goes through the queue. A busy call stack delays all queued callbacks. The browser is multi-threaded; is not.
EXERCISE
1The Delay Is a Minimum, Not a Guarantee
setTimeout(fn, 5000) does NOT guarantee that fn runs after exactly 5 seconds. It guarantees that fn will run after AT LEAST 5 seconds. It could be longer.
setTimeout(fn, 5000) does not promise to run fn in five seconds. It promises not to run it sooner than five seconds. The delay is a minimum, and the actual wait can be considerably longer.
The reason follows from the event loop. After the delay elapses, the callback joins the callback queue. It runs when the stack is empty and the microtask queue has been drained. If the thread is busy, it waits.
console.log("start");
setTimeout(function () {
console.log("timer fired at " + (Date.now() - t0) + "ms");
}, 100);
const t0 = Date.now();
const end = t0 + 2000;
while (Date.now() < end) {
// busy for two seconds
}
console.log("blocking finished");
The timer asked for 100 milliseconds and reports roughly 2000. Its delay expired on schedule and the callback was queued on time, then sat there because the thread was occupied by the loop.
Nothing here is broken. The timer did what it said: it waited at least 100 milliseconds.
The same is true of a zero delay:
console.log("first");
setTimeout(function () {
console.log("third");
}, 0);
console.log("second");
Zero means "as soon as possible", and the soonest possible moment is after the current code has finished. There is no way to ask for sooner, because interrupting running code is precisely what a single thread does not do.
Browsers also impose a floor. Nested timers are clamped to about four milliseconds once you go a few levels deep, and background tabs are throttled much harder, often to once per second or less. A tab that is not visible is not worth spending battery on.
This is why timers are the wrong tool for measuring elapsed time:
let ticks = 0;
setInterval(function () {
ticks += 1;
}, 1000);
After an hour, ticks will be less than 3600, and how much less depends on how busy the page was and whether it was in the background. If you need to know how much time has passed, ask the clock:
const started = Date.now();
setInterval(function () {
const seconds = Math.floor((Date.now() - started) / 1000);
console.log(seconds + "s elapsed");
}, 1000);
Counting invocations measures how often the callback ran. Subtracting timestamps measures time.
EXERCISE
2The Concurrency Model
JavaScript uses a concurrency model based on the event loop. It is not truly parallel, but it feels concurrent because it switches between tasks very quickly.
JavaScript's model is often summarised as "single-threaded and asynchronous", which sounds contradictory until you separate two things: what executes your code, and what does the waiting.
Only one thing executes your code, and that is the call stack. It handles one frame at a time and cannot be interrupted. Nothing runs in parallel with your functions.
The waiting is done by the environment, which is not limited to one thread at all. A browser can run several network requests, a handful of timers and a file read simultaneously, because those are handled by the browser's own machinery.
console.log("start");
setTimeout(() => console.log("timer 1"), 1000);
setTimeout(() => console.log("timer 2"), 1000);
setTimeout(() => console.log("timer 3"), 1000);
console.log("end");
Three timers counting the same second, concurrently, outside JavaScript. When they expire, their callbacks queue and run one at a time on the single thread. The waiting overlapped; the executing did not.
This is why parallel requests are faster than sequential ones even with one thread:
const urls = ["/a", "/b", "/c"];
urls.forEach(function (url) {
fetch(url).then(function (res) {
console.log(url, res.status);
});
});
All three requests are in flight at once. The network waiting overlaps completely. Only the handling of each response is serialised, and that part is fast.
What you cannot overlap is computation:
function heavy() {
let total = 0;
for (let i = 0; i < 500000000; i++) total += i;
return total;
}
setTimeout(heavy, 0);
setTimeout(heavy, 0);
Two timers, but no concurrency at all. Each heavy occupies the thread for its full duration, and the second waits for the first. Scheduling computation does not make it parallel; it only changes when the freeze starts.
The dividing line is the same one from earlier in this unit. Work that waits on something external can overlap, because the waiting is not done by JavaScript. Work that computes cannot, because computing is exactly what the single thread does.
applies the same model with a different cast: libuv and a small thread pool instead of Web APIs, the same single JavaScript thread, and the same event loop moving finished callbacks back onto it.
EXERCISE
3The Complete Async Picture
Let us put everything together: call stack, Web APIs, callback queue, microtask queue, and the event loop. This is the full mental model of async JavaScript.
Every piece of this unit fits into one picture. Here it is in full, and then traced once.
your code
|
v
+-----------------+ +----------------------+
| CALL STACK | ---> | WEB APIs |
| one frame at | | timers, fetch, DOM |
| a time | | these actually wait |
+-----------------+ +----------------------+
^ |
| v
| +----------------------+
| | MICROTASK QUEUE | promises
| +----------------------+
| |
| +----------------------+
+------------------- | CALLBACK QUEUE | timers, events
EVENT LOOP +----------------------+
stack empty?
drain microtasks, then take ONE callback
Three participants. The stack runs code. The Web APIs do the waiting, outside JavaScript. The event loop moves finished callbacks back to the stack, microtasks first, always.
console.log("1");
setTimeout(function () {
console.log("2");
}, 0);
Promise.resolve().then(function () {
console.log("3");
});
console.log("4");
1 and 4 run on the stack. The timer goes to the browser and its callback lands in the callback queue. The promise callback lands in the microtask queue. The stack empties, the loop drains microtasks and prints 3, then takes one callback and prints 2.
Output: 1, 4, 3, 2.
Five things are worth carrying out of this unit, because everything asynchronous you meet later rests on them.
JavaScript never waits. It delegates and continues. Any function that needs a value from an asynchronous operation must receive it through a callback rather than a return.
A delay is a minimum. The callback runs after the delay and after the thread is free.
Microtasks beat callbacks, every time. A promise scheduled after a zero-delay timer still runs first, and the microtask queue is drained completely between tasks.
Concurrency is in the waiting, not the executing. Requests overlap; computation does not.
Blocking the thread blocks everything. No clicks, no rendering, no timers, no exceptions.
Pro Tip: Promises and
async/await, which you will meet next, change none of this. They are a better way to write callbacks, scheduled on the microtask queue by the same loop, and every rule above still applies underneath.
