What Timers Actually Promise
setTimeout does not schedule a callback to run in N milliseconds. It schedules it to become eligible after N milliseconds.
A delay is a minimum, not a guarantee. Nested timers are clamped to 4ms, background tabs are throttled heavily, and a busy stack delays everything. setInterval compounds the problem by not waiting for its own callback to finish.
EXERCISE
1The Delay Is a Minimum
Every timer in JavaScript promises one thing only: not sooner than this.
The mental model most people carry is that setTimeout(fn, 100) runs fn in 100 milliseconds. What it actually does is move fn into the callback queue after 100 milliseconds. When it runs depends on what else is happening.
Measuring the difference:
const start = Date.now();
setTimeout(() => {
console.log(`asked for 100, waited ${Date.now() - start}`);
}, 100);
// Nothing else running: waited 101
// With a 2 second block: waited 2003
The timer was eligible on time in both cases. In the second it sat in the queue because the stack was busy, which is lesson 1's rule again.
So a delay is a floor, and these are all normal:
setTimeout(fn, 0); // "as soon as the stack is clear"
setTimeout(fn, 100); // "not before 100ms, probably a little after"
There is no upper bound at all. A timer on a busy page can be seconds late.
Nested timers get clamped to four milliseconds:
let count = 0;
const start = Date.now();
function tick() {
count++;
if (count < 10) setTimeout(tick, 0);
else console.log(`10 nested timers took ${Date.now() - start}ms`);
}
tick();
// 10 nested timers took about 40ms, not 0
After five levels of nesting, browsers force a minimum of 4ms. This is in the HTML specification, not a browser quirk, and it exists to stop a zero-delay recursion consuming a core. It is why the pattern from the last lesson has a real per-chunk cost.
Background tabs are throttled much harder:
// A tab the user is not looking at:
// timers are limited to roughly once per second,
// and after a few minutes, far less than that.
//
// Which means this is not a reliable clock:
setInterval(() => { secondsElapsed += 1; }, 1000);
// Compute elapsed time from a timestamp instead:
const started = Date.now();
setInterval(() => {
const elapsed = Math.floor((Date.now() - started) / 1000);
}, 1000);
Counting ticks assumes every tick happened. Reading the clock does not, and that is the difference between a timer that stays correct when the tab is backgrounded and one that silently loses minutes.
Pro Tip: Never derive time from how many times a timer fired. Take a timestamp when you start and subtract it when you need the elapsed value. That one habit makes your code correct under throttling, under blocking, and under a laptop being closed and reopened, none of which you can otherwise control.
EXERCISE
2setInterval and Why setTimeout Usually Wins
An interval does not wait for its own callback to finish, which is a problem the moment the callback is slow.
The difference in one picture:
// setInterval(fn, 1000) schedules fn every 1000ms regardless of
// how long fn takes:
//
// |--fn--| |--fn--| |--fn--|
// 0 1s 1s 2s 2s
//
// If fn takes 1500ms, the next one is already due when it finishes:
//
// |------fn------||------fn------||------fn------|
// no gap at all, and they queue up behind each other
Which matters most with anything over a network:
// Risky: a slow response means overlapping requests
setInterval(async () => {
const data = await fetch("/api/status");
render(data);
}, 1000);
// Safe: the next wait does not start until this one has finished
async function poll() {
const data = await fetch("/api/status");
render(data);
setTimeout(poll, 1000);
}
poll();
The second version guarantees a full second between runs rather than a second between starts. Requests can never overlap, and a temporarily slow slows the polling down rather than piling work up.
Read the two diagrams again with that in mind. An interval measures from start to start, which is a promise the callback has no way to keep once it is slower than the gap. A recursive timeout measures from end to start, which is a promise it can always keep because it does not schedule the next run until the current one is done.
Intervals also keep running until told otherwise:
const id = setInterval(tick, 1000);
clearInterval(id);
// Forgetting clearInterval in a component that unmounts, or a page
// section that is removed, leaves the callback running forever and
// holding everything it closed over in memory.
This is one of the most common real memory leaks in front-end code, and Unit 11 comes back to it.
A recursive timeout is also easy to cancel and to back off:
let timerId = null;
let delay = 1000;
async function poll() {
try {
render(await fetch("/api/status"));
delay = 1000; // success: back to normal
} catch {
delay = Math.min(delay * 2, 30000); // failure: back off
}
timerId = setTimeout(poll, delay);
}
poll();
// later: clearTimeout(timerId);
Exponential backoff is not possible with setInterval at all, because the delay is fixed when the interval is created.
Default to a recursive setTimeout for anything that repeats and does real work, and keep setInterval for cheap, fixed-cost ticks like updating a clock display. The recursive form costs one extra line and gives you non-overlapping runs, an adjustable delay, and a cancel that actually stops things.
EXERCISE
3Cancelling, and Cleaning Up
Every timer you start is a reference the engine holds until you stop it, and forgetting is one of the easiest leaks to create.
setTimeout and setInterval both return an id, and that id is the only way to stop them.
The basic form:
const timeoutId = setTimeout(() => console.log("never"), 1000);
clearTimeout(timeoutId);
const intervalId = setInterval(tick, 1000);
clearInterval(intervalId);
clearTimeout and clearInterval are interchangeable in practice, but matching them to what you created keeps the intent readable.
Why a forgotten timer is a leak, not just a stray callback:
function setUpWidget(element, data) {
setInterval(() => {
element.textContent = data.value;
}, 1000);
}
The callback closes over element and data, so neither can be garbage collected while the interval lives. Remove the element from the page and it stays in memory, along with everything it references, forever. The callback also keeps writing to a nobody can see.
The shape that avoids it: hand back a way to stop.
function setUpWidget(element, data) {
const id = setInterval(() => {
element.textContent = data.value;
}, 1000);
return () => clearInterval(id);
}
const stop = setUpWidget(node, data);
// when the widget goes away:
stop();
Returning a cleanup function is the standard pattern, and it is exactly what 's useEffect expects you to return for this reason.
A timeout you might want to cancel from elsewhere:
let searchTimer = null;
input.addEventListener("input", (event) => {
clearTimeout(searchTimer);
searchTimer = setTimeout(() => {
search(event.target.value);
}, 300);
});
Each keystroke cancels the pending search and starts a new one, so search runs only once the typing stops. That is debouncing, and Unit 10 builds it properly as a reusable function. It is here because it is the clearest example of a timer id being worth keeping.
And one behaviour worth knowing about ids:
const id = setTimeout(() => {}, 0);
console.log(typeof id);
// "number" in a browser, an object in Node
clearTimeout(999999); // clearing an id that does not exist: no error
Clearing an already-fired or non-existent timer is always safe, which means cleanup code never needs to check first.
