Timers: setTimeout & setInterval
Learn how to delay or repeat code in JavaScript with setTimeout and setInterval, and how to cancel them with clearTimeout and clearInterval.
On this page
1. What are timers?
Both functions take a callback and a delay in milliseconds. This feature is not part of the JavaScript language itself, it is provided by the browser and Node.js.
Every timer returns an id. You can use that id to cancel the timer.
2. Why does it matter?
Many tasks should not happen right away, but a little later or repeatedly, like hiding a toast message after 3 seconds or updating a clock every second.
| Without timers | With timers |
|---|---|
| An empty loop for a delay, the page freezes | A non-blocking delay, the page keeps working |
| Manual tricks for repeating | A clean repeat with setInterval |
| Hard to cancel the work | clearTimeout and clearInterval |
| Hard to give the user feedback | Toasts, countdowns, and polling are easy |
3. Where is it used?
| Use case | Timer |
|---|---|
| Toast notification | Hide after 3s with setTimeout |
| Digital clock | setInterval every 1000ms |
| Countdown / OTP resend | setInterval, cleared at the end |
| Search debounce | setTimeout, cleared on every keypress |
| Polling | Check the server every few seconds |
4. How does it work?
| Function | Job |
|---|---|
setTimeout(fn, ms) | Once, after ms |
setInterval(fn, ms) | Every ms, until cleared |
clearTimeout(id) | Cancel a pending timeout |
clearInterval(id) | Stop the interval |
5. Code example
A toast that hides after 3 seconds
function showToast(message) {
const toast = document.querySelector("#toast");
toast.textContent = message;
toast.hidden = false;
const id = setTimeout(() => {
toast.hidden = true;
}, 3000);
return () => clearTimeout(id);
}
const cancel = showToast("Saved!");A countdown that stops itself
let seconds = 5;
const intervalId = setInterval(() => {
console.log(seconds);
seconds--;
if (seconds < 0) {
clearInterval(intervalId);
console.log("Time up");
}
}, 1000);A promise-based delay
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
await wait(1000);
console.log("After 1 second");How does the code work?
| Line | What is happening |
|---|---|
const id = setTimeout(...) | Saves the timer id so you can cancel later |
return () => clearTimeout(id) | Returns a cancel function, the caller can stop it if needed |
setInterval(..., 1000) | The callback runs every second |
clearInterval(intervalId) | Stops the interval once the condition is met |
wait(ms) | Wraps the timer in a promise to use with await |
6. Common mistakes
Mistake: Passing a function call instead of a callback
Why? In setTimeout(save(), 1000), save runs immediately and its return value is given to the timer.
Better: Pass a function reference or an arrow function: setTimeout(save, 1000) or setTimeout(() => save(id), 1000).
Mistake: Never clearing a setInterval
Why? The interval keeps running forever, causing memory leaks and duplicate work.
Better: Save the id and call clearInterval when the work is done or the component is removed.
Mistake: Trusting exact timing
Why? With a busy stack or in a background tab, the browser delays or throttles timers.
Better: For accurate time, calculate the real elapsed time with Date.now().
Mistake: Using setInterval for async work
Why? If a request takes 2 seconds and the interval is 1 second, the requests overlap.
Better: Schedule the next setTimeout when the work finishes (recursive setTimeout).
7. What to learn before and after
| Stage | Topics |
|---|---|
| Before | Functions, Arrow Functions, Event Loop |
| After | Callbacks, Promises, Debounce & Throttle |
Final quick revision
| Point | Detail |
|---|---|
setTimeout | Once, after a delay |
setInterval | Again and again, until cleared |
| Timer id | Save it so you can cancel |
| Delay | A minimum time, not a guarantee |
| Promise delay | new Promise((r) => setTimeout(r, ms)) |