Timers
Timers schedule a function to run later: once after a delay with setTimeout, or repeatedly with setInterval. They power reminders, auto-saving, polling a server, debouncing a search box and countdown displays. Timers are provided by the runtime, not the JavaScript language, but both browsers and Node.js have them with the same names. The key fact to understand: a timer's delay is a minimum, because the callback can only run when the main thread is free.
In One Minute
setTimeout(fn, ms, ...args)runsfnonce after at leastmsmilliseconds; it returns an ID.setInterval(fn, ms)runsfneverymsmilliseconds until stopped.clearTimeout(id)andclearInterval(id)cancel them.- Delays are minimums: callbacks wait for the current code to finish, and browsers slow timers in background tabs.
- For animation, use
requestAnimationFrame; for repeated async work, prefer a recursivesetTimeout.
setTimeout
Syntax
const id = setTimeout(callback, delayInMs, arg1, arg2);
clearTimeout(id);Example
console.log("Payment saved");
setTimeout(() => {
console.log("Receipt emailed (after 50 ms)");
}, 50);
setTimeout((name, amount) => {
console.log(`Reminder: ${name} owes $${amount}`);
}, 10, "Srihitha", 85);
console.log("Back to the user right away");Payment saved
Back to the user right away
Reminder: Srihitha owes $85
Receipt emailed (after 50 ms)Explanation: setTimeout doesn't pause the program. It registers the function and returns immediately, so "Back to the user right away" prints second. The callbacks run later, in order of when they're due: the 10 ms timer before the 50 ms one. Extra arguments after the delay are passed to the callback.
Canceling a Timeout
setTimeout returns an ID (a number in browsers, an object in Node.js). Pass it to clearTimeout to cancel before it runs:
const undo = setTimeout(() => console.log("Payment deleted"), 30);
console.log("Delete scheduled. Undo?");
setTimeout(() => {
clearTimeout(undo);
console.log("Undone: nothing was deleted");
}, 10);Delete scheduled. Undo?
Undone: nothing was deletedThis is the "Undo" pattern: delay a destructive action briefly and cancel it if the user changes their mind. Calling clearTimeout with an ID that already ran, or with undefined, does nothing and doesn't throw.
setInterval
setInterval repeats a function at a fixed interval until you clear it:
let secondsLeft = 3;
const id = setInterval(() => {
console.log(`Session ends in ${secondsLeft}...`);
secondsLeft--;
if (secondsLeft === 0) {
clearInterval(id);
console.log("Session ended");
}
}, 20);Session ends in 3...
Session ends in 2...
Session ends in 1...
Session endedDelays Are Minimums
A timer callback can only run when the call stack is empty: JavaScript finishes whatever it is doing first. A long task delays every timer:
const start = Date.now();
setTimeout(() => {
const waited = Date.now() - start;
console.log(`Asked for 10 ms, waited at least 100 ms: ${waited >= 100}`);
}, 10);
while (Date.now() - start < 100) {
// a slow calculation that blocks the main thread for 100 ms
}
console.log("Slow work done");Slow work done
Asked for 10 ms, waited at least 100 ms: trueExplanation: the timer was due after 10 ms, but the loop held the main thread for 100 ms, so the callback had to wait. The exact time differs per run, so the example prints only whether it waited at least 100 ms.
Other reasons a timer runs late:
| Cause | Effect |
|---|---|
| Busy main thread | Waits until current code finishes |
| Nested timers | After 5 levels of nesting, browsers enforce at least 4 ms |
| Background tab | Browsers throttle timers to about once per second, or less |
| Sleeping device | Timers don't run at all while asleep |
setTimeout(fn, 0) | Still waits for the current code and other queued tasks |
So never use timers for precise timekeeping. A countdown should compute the remaining time from the clock (Date.now() or performance.now()) on each tick, not count ticks.
Recursive setTimeout vs setInterval
setInterval fires on a fixed schedule even if the previous callback hasn't finished its work (for example, a slow network request). A recursive setTimeout schedules the next run only after the current one completes, so runs never overlap and the gap is always respected:
let checks = 0;
function pollForPayments() {
checks++;
console.log(`Checking for new payments (#${checks})`);
if (checks < 3) {
setTimeout(pollForPayments, 20);
} else {
console.log("Stopped polling");
}
}
pollForPayments();Checking for new payments (#1)
Checking for new payments (#2)
Checking for new payments (#3)
Stopped pollingThis shape is also easy to extend with backoff (waiting longer after each failure) and to stop cleanly. Use it for polling servers; the async chapter adds await to it.
Timers and this
Passing a method directly to a timer loses its this, because the timer calls it as a plain function:
const reminder = {
studentName: "Advitha",
send() {
console.log(`Reminder sent to ${this?.studentName}`);
},
};
setTimeout(reminder.send, 0);
setTimeout(() => reminder.send(), 0);Reminder sent to undefined
Reminder sent to AdvithaWrap the call in an arrow function, or use reminder.send.bind(reminder).
Promise-Based Timers
A delay that can be awaited is a one-line promise wrapper (promises and await are explained in the async chapter). Node.js also provides one built in, in node:timers/promises:
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
console.log("Saving...");
await sleep(20);
console.log("Saved");Saving...
SavedIn Practice
The Fee Tracker auto-saves a note a short time after the person stops typing, instead of on every keystroke. This pattern is called debouncing: each keystroke cancels the pending save and schedules a new one:
<textarea id="note"></textarea>
<p id="status"></p>
<script>
const note = document.querySelector("#note");
const status = document.querySelector("#status");
let timer;
note.addEventListener("input", () => {
status.textContent = "Typing...";
clearTimeout(timer);
timer = setTimeout(() => {
status.textContent = `Saved: "${note.value}"`;
console.log(status.textContent);
}, 250);
});
</script>Saved: "Paid by check"The checker changed the note twice within 250 ms; only the final value was saved, once. The performance lesson turns this into a reusable debounce function.
Common Mistakes
Forgetting to clear intervals. They run forever and leak memory. Store the ID and call clearInterval.
Expecting exact timing. Delays are minimums. Compute elapsed time from the clock.
Passing a string to setTimeout. setTimeout("save()", 100) evaluates code from a string, like eval; it's blocked by Content Security Policy. Pass a function.
Calling the function instead of passing it. setTimeout(save(), 100) runs save now.
Practice
Challenge: Write countdown(n, ms) that logs n, n-1... down to 1 with ms between each, then logs "Go!", using recursive setTimeout.
Show solution
function countdown(n, ms) {
if (n === 0) {
console.log("Go!");
return;
}
console.log(n);
setTimeout(() => countdown(n - 1, ms), ms);
}
countdown(3, 10);3
2
1
Go!Key Takeaways
| Task | Code |
|---|---|
| Run once later | const id = setTimeout(fn, ms) |
| Cancel | clearTimeout(id) |
| Repeat | const id = setInterval(fn, ms) |
| Stop repeating | clearInterval(id) |
| Await a delay | await new Promise((r) => setTimeout(r, ms)) |
Was this tutorial helpful?