Event loop
One thread
JavaScript runs user code on one thread with an event loop around it. Async tasks wait in the background while the thread handles ready callbacks one by one. This model stays simple as long as no single callback hogs the thread. The program shows the order: the two plain logs run first, and the zero-delay timer runs after them.
console.log("first"); setTimeout(() => { console.log("timer"); }, 0); console.log("second");
first
second
timer
Micro vs macro
Promise callbacks are micro tasks and timer callbacks are macro tasks. After each main turn the loop drains all ready micro tasks before the next timer. That is why a resolved promise prints before a zero delay timer. The program also logs a plain line at the end, so all three kinds of work appear in one run: the plain line first, the promise next, the timer last.
setTimeout(() => { console.log("macro"); }, 0); Promise.resolve("value").then((v) => { console.log(v); }); console.log("sync");
sync
value
macro
Do not block
A long tight loop blocks timers, network events, and promise progress. Split heavy work into chunks and yield with a short timer or an awaited delay between chunks. The loop then stays responsive while total speed stays close to the same. The program prints three numbers and yields between them, so a timer could run in each pause.
async function chunks(): Promise<void> { for (let i = 0; i < 3; i++) { console.log(i); await new Promise((resolve) => setTimeout(resolve, 0)); } } chunks();
0
1
2
Measure with console.time
Use console dot time around an await to learn the real wait. Start the timer, await the work, then stop the timer with the same label; the number that console dot timeEnd prints changes on every run, so it cannot stand in this page as fixed text. The program therefore measures the same wait with performance dot now and prints only the fact that holds every time, which is that the wait lasted at least the 50 milliseconds it asked for. Compare serial and parallel shapes on real data before tuning.
async function timed(): Promise<void> { const start = performance.now(); await new Promise((resolve) => { setTimeout(resolve, 50); }); const waited = performance.now() - start; console.log("waited at least 50 ms: " + (waited >= 50)); } timed();
waited at least 50 ms: true
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
How does JavaScript run the code of a program?
Answer
On one thread, with an event loop that runs ready callbacks
User code runs on a single thread, and the event loop hands it one ready callback at a time.
-
After the current turn, which callbacks run before the next timer?
Answer
The ready promise callbacks, because micro tasks drain first
The loop drains every ready micro task after a turn, and a timer is a macro task that waits for the next turn.
-
Why split heavy work into chunks with a pause between them?
Answer
Chunks let timers and network events run between the pieces
A tight loop holds the thread, while a pause gives the loop a turn to run other ready callbacks.
-
What do
console.timeandconsole.timeEndwith the same label print?Answer
One line with the time between the two calls
The pair prints the elapsed milliseconds under that label, which is what makes it a quick measure of a wait.
-
What does this program print?
console.log("first"); setTimeout(() => { console.log("timer"); }, 0); console.log("second");Answer
first / second / timer
The two plain logs run during the main turn, and the zero-delay timer waits for the next turn.
-
What does this program print?
setTimeout(() => { console.log("macro"); }, 0); Promise.resolve("value").then((v) => { console.log(v); });Answer
value / macro
The promise callback is a micro task and runs before the timer, which is a macro task.
-
What does this program print?
Promise.resolve(1).then((n) => { console.log(n + 1); }); console.log("start");Answer
start / 2
The plain log runs in the current turn, and the then callback runs after it as a micro task.
-
What does this program print?
Promise.resolve("a").then((v) => { console.log(v); Promise.resolve("b").then((w) => { console.log(w); }); }); setTimeout(() => { console.log("timer"); }, 0);Answer
a / b / timer
The first callback queues a second micro task, and both micro tasks drain before the timer gets its turn.
-
A callback runs a tight loop for two seconds, and a zero-delay timer is waiting. What happens to the timer?
Answer
It waits until the loop returns and the thread is free
The thread cannot run the timer callback while the loop holds it, so the timer fires after the loop ends.
-
Why can a page not show the exact line of
console.timeEndas fixed output?Answer
The measured number of milliseconds changes from run to run
A timing depends on the machine and its load, so each run prints a different duration and no single line is the truth.
Article author: Arthur Isaev