Skip to content
Async JavaScriptChapter 31 / 47Beginner4 min read

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 timersWith timers
An empty loop for a delay, the page freezesA non-blocking delay, the page keeps working
Manual tricks for repeatingA clean repeat with setInterval
Hard to cancel the workclearTimeout and clearInterval
Hard to give the user feedbackToasts, countdowns, and polling are easy

3. Where is it used?

Use caseTimer
Toast notificationHide after 3s with setTimeout
Digital clocksetInterval every 1000ms
Countdown / OTP resendsetInterval, cleared at the end
Search debouncesetTimeout, cleared on every keypress
PollingCheck the server every few seconds

4. How does it work?

The journey of setTimeout
setTimeout is called and returns an id
The browser counts the time
When time is up, the callback goes into the task queue
When the stack is empty, the event loop runs the callback
FunctionJob
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

js
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

js
let seconds = 5;

const intervalId = setInterval(() => {
  console.log(seconds);
  seconds--;

  if (seconds < 0) {
    clearInterval(intervalId);
    console.log("Time up");
  }
}, 1000);

A promise-based delay

js
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

await wait(1000);
console.log("After 1 second");

How does the code work?

LineWhat 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

Suggested order
Event Loop
Timers
Callbacks
Promises
Debounce and Throttle

Final quick revision

PointDetail
setTimeoutOnce, after a delay
setIntervalAgain and again, until cleared
Timer idSave it so you can cancel
DelayA minimum time, not a guarantee
Promise delaynew Promise((r) => setTimeout(r, ms))