Why doesn't setTimeout(…, 0) fire at once?
The event loop: why "in 0 milliseconds" means "after all the current code", and why try without await catches nothing.
console.log("order taken");
setTimeout(() => console.log("timer"), 0);
async function kitchen() {
console.log("the cook takes the order");
await null;
console.log("the cook is back after await");
}
kitchen();
Promise.resolve().then(() => console.log("promise"));
console.log("end of code");The order is: "order taken", "the cook takes the order", "end of code", "the cook is back after await", "promise", "timer".
Three surprises:
JavaScript has one thread: at any moment exactly one task runs. It works like this:
1. First, all the current synchronous code runs — to the end. 2. Then the engine runs the microtasks — callbacks of settled promises (then, continuations after await). 3. Then it takes the next task from the queue — say, a timer that fired or a user's click.
That's the event loop. A 0 ms timer simply puts its callback in the task queue — "as soon as you're free". And the engine is only free after the current code and all the microtasks.
const start = Date.now();
setTimeout(() => console.log("the timer was late by", Date.now() - start, "ms"), 0);
while (Date.now() - start < 200) {
// busy: counting 200 ms
}
console.log("the loop finished");Two practical rules follow:
- the delay in setTimeout is a minimum, not an exact time;
- heavy computations mustn't hold the thread for long — split them into parts or move them to a Web Worker.
The event loop also explains the sneakiest bug in async code. try...catch catches errors that happen while its block is running. A promise rejects later — in another task, long after the try block has finished.
function burntPizza() {
return new Promise((resolve, reject) => {
setTimeout(() => reject(new Error("the pizza burnt")), 50);
});
}
async function withoutAwait() {
try {
return burntPizza();
} catch {
return "a spare pizza";
}
}
async function withAwait() {
try {
return await burntPizza();
} catch {
return "a spare pizza";
}
}
withAwait().then((food) => console.log("with await:", food));
withoutAwait()
.then((food) => console.log("without await:", food))
.catch((error) => console.log("without await the error slipped past catch:", error.message));await.In withoutAwait, the try block hands back the promise and finishes at once: no errors yet. 50 ms later the promise rejects, but no catch is listening any more — the rejection flies on to whoever called the function.
In withAwait, the function stays inside `try` while it waits. The rejection comes back into it as an exception right on the await line — and catch catches it. That's why inside try you write return await, not just return.
With that in mind you can write a retry — something every app on a flaky network does. Try; if it fails, try again, but not forever. The key is await inside try, or a failed attempt won't even be noticed.
let attempts = 0;
function shakyOven() {
attempts += 1;
return new Promise((resolve, reject) => {
setTimeout(() => {
if (attempts < 3) reject(new Error("the oven went cold"));
else resolve("pizza");
}, 20);
});
}
async function retry(task, times) {
for (let attempt = 1; attempt <= times; attempt++) {
try {
return await task();
} catch (error) {
console.log("Attempt " + attempt + ": " + error.message);
if (attempt === times) throw error;
}
}
}
retry(shakyOven, 5).then((food) => console.log("Done: " + food + ", attempts: " + attempts));retry would honestly throw the last error.Real apps also wait between attempts, longer each time: 1 s, 2 s, 4 s. If a server is overloaded, instant retries from a thousand clients will only finish it off. And you only retry what's safe to repeat: loading the menu — sure; charging a card — think first.
try without await is a night watchman who went home before the burglar showed up.Myth or fact?
Decide whether the statement is true. Got it wrong? Try again; once you're right, Byte explains what's going on.