JavaScript Timers & Event Loop
JavaScript runs your code on a single thread: it can only do one thing at a time. Yet web pages handle clicks, timers and network responses "at the same time". The secret is the event loop, which schedules work in small pieces. Understanding it explains exactly when your callbacks, timers and promise handlers run.
Timers
| Function | Does |
|---|---|
setTimeout(fn, ms, ...args) |
calls fn once, after at least ms milliseconds |
setInterval(fn, ms, ...args) |
calls fn repeatedly, every ms milliseconds |
clearTimeout(id) / clearInterval(id) |
cancels a timer using the id it returned |
const id = setTimeout(() => console.log("this never runs"), 100);
clearTimeout(id);
setTimeout((name) => console.log(`Hello, ${name}!`), 50, "Sam");
let ticks = 0;
const intervalId = setInterval(() => {
ticks++;
console.log("tick", ticks);
if (ticks === 3) {
clearInterval(intervalId);
console.log("stopped");
}
}, 100);Hello, Sam!
tick 1
tick 2
tick 3
stopped
Note: The delay is a minimum, not a guarantee. If the thread is busy, the callback waits until it's free. Browsers also clamp very short nested timers to about 4 ms.
The event loop in four parts
- Call stack — the function currently running, plus the functions that called it. JavaScript runs whatever is on the stack until it's empty.
- Web APIs / host — timers, network requests and event listeners are handled by the browser (or Node) outside the JavaScript thread.
- Task queue (macrotasks) — when a timer expires or an event fires, its callback is put in this queue.
- Microtask queue — promise reactions (
then,catch,awaitcontinuations) andqueueMicrotaskcallbacks go here.
The loop repeats: run one task to completion → run all microtasks → (browser may render) → take the next task.
Ordering: sync, microtasks, tasks
This is the classic puzzle — try to predict the output before reading it:
console.log("1: synchronous");
setTimeout(() => console.log("5: timeout (task)"), 0);
Promise.resolve().then(() => console.log("3: promise (microtask)"));
queueMicrotask(() => console.log("4: queueMicrotask (microtask)"));
console.log("2: synchronous");1: synchronous
2: synchronous
3: promise (microtask)
4: queueMicrotask (microtask)
5: timeout (task)
Even with a 0 ms delay, the timeout comes last: synchronous code always finishes first, then every microtask runs, and only then is the next task (the timer callback) taken from the queue.
await and the microtask queue
Code after an await is scheduled as a microtask, so it runs after the current synchronous code but before any timers:
async function work() {
console.log("B: work starts");
await null;
console.log("D: work resumes after await");
}
console.log("A: start");
setTimeout(() => console.log("E: timer"), 0);
work();
console.log("C: end of script");A: start
B: work starts
C: end of script
D: work resumes after await
E: timer
Blocking the thread
Because there's only one thread, a long-running loop blocks everything — timers, clicks and page rendering all wait:
setTimeout(() => console.log("timer (asked for 0 ms) finally runs"), 0);
console.log("starting a long calculation…");
let sum = 0;
for (let i = 0; i < 50_000_000; i++) {
sum += i % 7; // keeps the thread busy for a noticeable moment
}
console.log("calculation finished:", sum);starting a long calculation…
calculation finished: 149999997
timer (asked for 0 ms) finally runs
The timer was due almost immediately, but it had to wait until the loop — and the rest of the script — finished. In a real page, the UI would freeze for the whole calculation. Heavy computations belong in a Web Worker (a separate thread) or should be split into small chunks with setTimeout.
A promise-based sleep
Wrapping setTimeout in a promise gives you a handy sleep you can await:
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
for (const n of [3, 2, 1]) {
console.log(n + "…");
await sleep(100);
}
console.log("Go!");3…
2…
1…
Go!
Summary
| Kind of work | Queue | Runs |
|---|---|---|
| Your script, function calls | call stack | immediately |
then/catch/finally, code after await, queueMicrotask |
microtask queue | as soon as the stack is empty, all of them |
setTimeout, setInterval, events, network callbacks |
task queue | one per loop turn, after microtasks |
Test yourself
Which runs first after the current script ends: a resolved promise's then callback or a setTimeout(fn, 0) callback?
- The setTimeout callback
- The then callback
- Random order
- They run in parallel
What does setTimeout(fn, 1000) guarantee?
- fn runs exactly after 1000 ms
- fn runs no earlier than about 1000 ms
- fn runs within 1000 ms
- fn runs on another thread
How do you stop a setInterval?
- clearTimeout(fn)
- clearInterval(id) with the id it returned
- return false from the callback
- It stops after 10 calls