Many programs need to do something later: hide a message after three seconds, refresh a score every minute, or give up on a slow request. JavaScript does this with timers. setTimeout runs a function once after a delay, and setInterval runs it again and again. Combined with promises, timers also give you a sleep() function, timeouts for slow work, and automatic retries. This lesson covers all of these, with real timings so you can see exactly when each line runs.
In this lesson you will learn
setTimeoutandclearTimeoutsetIntervalandclearInterval- Why a delay of 0 still waits
- A promise-based
sleep()forasynccode - Timeouts with
Promise.raceand retrying failed work
You should know promises and async/await. The event loop lesson explains what happens behind the scenes.
setTimeout and setInterval
"use strict";
const start = Date.now();
const t = () => `${Math.round((Date.now() - start) / 100) * 100}ms`; // rounded elapsed time
// setTimeout runs a function once, after a delay in milliseconds
setTimeout(() => console.log(t(), "timeout 300 done"), 300);
setTimeout(() => console.log(t(), "timeout 100 done"), 100);
// clearTimeout cancels a timer before it runs
const cancelled = setTimeout(() => console.log("this never prints"), 200);
clearTimeout(cancelled);
// setInterval repeats until cleared
let ticks = 0;
const id = setInterval(() => {
ticks++;
console.log(t(), "tick", ticks);
if (ticks === 3) {
clearInterval(id);
console.log(t(), "interval stopped");
}
}, 200);
// A delay of 0 still waits until the current code has finished
setTimeout(() => console.log(t(), "zero-delay timeout"), 0);
console.log(t(), "end of script");
Output
0ms end of script
0ms zero-delay timeout
100ms timeout 100 done
200ms tick 1
300ms timeout 300 done
400ms tick 2
600ms tick 3
600ms interval stopped
setTimeout(fn, ms)schedulesfnto run once after aboutmsmilliseconds and returns an ID. The script does not stop and wait: “end of script” prints first.- Timers run in order of their due time, not the order they were created, so the 100ms timeout fires before the 300ms one.
clearTimeout(id)cancels a timer that has not run yet. The cancelled message never appears.setInterval(fn, ms)repeats everymsmilliseconds untilclearInterval(id)is called. Forgetting to clear an interval leaves it running forever.- A delay of
0does not mean “now”. The callback waits until the current script has finished, which is why it prints after “end of script”. - The delay is a minimum. If the program is busy, a timer can fire later than requested, so never use timers for exact timekeeping. Compare against
Date.now()instead, as this example does.
Timers with Promises
"use strict";
// A promise-based sleep lets you pause inside async functions
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
// Countdown with a for loop and await
async function countdown(from) {
for (let n = from; n > 0; n--) {
console.log(`${n}...`);
await sleep(100);
}
console.log("Exam starts now!");
}
// A timeout for slow work: whichever promise settles first wins
function withTimeout(promise, ms) {
let timer;
const timeout = new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error(`timed out after ${ms}ms`)), ms);
});
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
}
// Retry with a growing wait between attempts
async function retry(task, attempts) {
for (let i = 1; i <= attempts; i++) {
try {
return await task(i);
} catch (e) {
console.log(`attempt ${i} failed: ${e.message}`);
if (i === attempts) throw e;
await sleep(50 * i);
}
}
}
async function main() {
await countdown(3);
console.log(await withTimeout(sleep(50).then(() => "fast result"), 200));
try {
await withTimeout(sleep(500), 200);
} catch (e) {
console.log("Error:", e.message);
}
const result = await retry(async n => {
if (n < 3) throw new Error("server busy");
return "saved on attempt " + n;
}, 4);
console.log(result);
}
main();
Output
3...
2...
1...
Exam starts now!
fast result
Error: timed out after 200ms
attempt 1 failed: server busy
attempt 2 failed: server busy
saved on attempt 3
sleep(ms)wrapssetTimeoutin a promise. Inside anasyncfunction,await sleep(100)pauses that function without freezing the rest of the program.- The countdown loop reads like ordinary step-by-step code, which is much clearer than nesting several
setTimeoutcalls. withTimeoutraces the real work against a timer that rejects.Promise.racesettles with whichever finishes first. The fast job wins its race; the slow one loses and becomes an error.finallyclears the timer so it does not linger.retrytries a task several times, waiting a little longer after each failure. This pattern, called backoff, is common for network requests to busy servers.
Timer Functions
| Function | Does |
|---|---|
setTimeout(fn, ms, ...args) | Run fn once after at least ms; returns an ID |
clearTimeout(id) | Cancel a pending timeout |
setInterval(fn, ms) | Run fn every ms; returns an ID |
clearInterval(id) | Stop an interval |
requestAnimationFrame(fn) | Run fn before the next screen repaint (browser animations) |
AbortSignal.timeout(ms) | A signal that cancels fetch after ms |
Common Mistakes
- Calling the function instead of passing it:
setTimeout(show(), 1000)runsshowimmediately. WritesetTimeout(show, 1000)or use an arrow function. - Never clearing intervals, especially when a page section or component is removed.
- Using a loop of timeouts for animation.
requestAnimationFrameor CSS animations are smoother. - Expecting
awaitinsideforEachto wait. Use afor...ofloop, as the countdown does.
Practice Exercises
Exercise 1. Print “Saved!” and then remove the message after 2 seconds, in the browser.
Show answer
const msg = document.getElementById("status");
msg.textContent = "Saved!";
setTimeout(() => { msg.textContent = ""; }, 2000);
Exercise 2. Write a clock that prints the time every second, and stops after 5 ticks.
Show answer
let n = 0;
const id = setInterval(() => {
console.log(new Date().toLocaleTimeString());
if (++n === 5) clearInterval(id);
}, 1000);
Frequently Asked Questions
Why do my timers run slowly in a background tab?
Browsers slow down timers in hidden tabs to save battery, often to once per second or less. Code that needs accurate elapsed time should measure it with Date.now() or performance.now() instead of counting ticks.
Is setInterval or a repeated setTimeout better?
A setTimeout that schedules the next one when it finishes guarantees a full gap between runs, even if each run is slow. setInterval fires on a fixed schedule, so slow callbacks can bunch up. For network polling, the repeated setTimeout is usually safer.
Summary
setTimeoutruns once;setIntervalrepeats; both return an ID for clearing.- Delays are minimums, and even 0 waits for the current code to finish.
await sleep(ms)pauses anasyncfunction cleanly.Promise.raceadds timeouts; retry with growing delays for flaky work.
