JavaScriptIntermediate

JavaScript Timers: setTimeout and setInterval Explained

Learn setTimeout, setInterval, clearTimeout and clearInterval with simple examples: delays, countdowns, live clocks, auto-hide messages and search delay.

All JavaScript lessons (83)View curriculum

What you will learn

In the last lesson you learned that asynchronous code starts a task and moves on, and that the browser does the waiting. The easiest way to see this in action is a timer. JavaScript has four timer functions:

  • setTimeout() runs a function once, after a delay
  • setInterval() runs a function again and again, after every delay
  • clearTimeout() cancels a setTimeout
  • clearInterval() cancels a setInterval

You have already used setTimeout in many lessons. In this lesson you will finally learn it properly, with all its details, and you will use timers to build real things: auto-hiding messages, a live clock, an OTP countdown, a rotating banner and a search box that waits for the user to stop typing.

The big idea: alarms on your phone

Think of the alarm app on your phone:

On your phone In JavaScript
“Wake me up once, 10 minutes from now” setTimeout(fn, 600000)
“Wake me up every day at 7” setInterval(fn, ...)
“Cancel that alarm” clearTimeout(id) or clearInterval(id)
The alarm’s number in your alarm list The timer ID that setTimeout and setInterval return

An alarm is a perfect example of asynchronous code. You set it and go on with your life. You do not stand and stare at the clock. When it rings, you stop what you are doing and handle it.

And remember the last lesson: if you are busy on a long call when the alarm rings, you only notice it after the call. JavaScript timers work the same way. A timer never interrupts running code. It waits for JavaScript to be free.

setTimeout: run once, later

setTimeout(function, delay);

It takes two main parts:

  1. The function to run later (the callback).
  2. The delay, in milliseconds.

A millisecond is one thousandth of a second. This is where beginners make mistakes, so keep this table in mind:

Milliseconds Time
500 half a second
1000 1 second
2000 2 seconds
60000 1 minute

Here is the simplest example:

console.log("Order placed");

setTimeout(function () {
  console.log("Order ready!");
}, 1000);

Output:

Order placed
Order ready!

(The second line appears 1 second later.)

JavaScript does not pause at setTimeout. It starts the timer, moves on, and runs the function after the delay. This is exactly the non-blocking behaviour you learned in the last lesson.

Pass the function, do not call it

You must give setTimeout the function itself, not the result of calling it. This was explained in the function concepts lesson, and timers are where the mistake is most common:

function greet() {
  console.log("Hello!");
}

setTimeout(greet, 1000);     // correct: pass the function
setTimeout(greet(), 1000);   // wrong: calls greet immediately

With greet() (with brackets), the function runs right now, and setTimeout receives undefined, so nothing useful is scheduled for later.

Sending values to the function

Everything after the delay is passed to your function as arguments:

function greet(name) {
  console.log("Hello, " + name);
}

setTimeout(greet, 500, "Riya");

Output:

Hello, Riya

An arrow function inside the timer does the same job and is more common today:

const name = "Riya";

setTimeout(() => {
  console.log("Hello, " + name);
}, 500);

Real use case 1: auto-hide a message

A message that disappears by itself is one of the most common uses of setTimeout. You met a toast message in the creating and removing elements lesson. Here is the idea in a smaller form, using classList from its own lesson:

<button id="save">Save</button>
<p id="notice" class="hidden">Saved successfully!</p>
const saveButton = document.getElementById("save");
const notice = document.getElementById("notice");

saveButton.addEventListener("click", function () {
  notice.classList.remove("hidden");   // show

  setTimeout(function () {
    notice.classList.add("hidden");    // hide again after 3 seconds
  }, 3000);
});

The timer ID and clearTimeout

Every time you call setTimeout, it gives you back a number. This is the timer ID. It is like the number of an alarm in your alarm list, and it is the only way to cancel that alarm later.

const id = setTimeout(function () {
  console.log("This will run");
}, 5000);

console.log(id);   // a number, such as 1

To cancel, give the ID to clearTimeout:

clearTimeout(id);

Real use case 2: “Undo send”

Many email apps wait a few seconds before they really send your mail, so you can change your mind:

const sendId = setTimeout(() => console.log("Email sent"), 2000);
console.log("Email will be sent in 2 seconds...");

// The user clicks "Undo" after 0.7 seconds:
setTimeout(() => {
  clearTimeout(sendId);
  console.log("Send cancelled");
}, 700);

Output:

Email will be sent in 2 seconds...
Send cancelled

The text Email sent is never printed, because the timer was cancelled before it rang.

Tip: Calling clearTimeout on a timer that has already finished, or on an ID that does not exist, is harmless. Nothing happens and there is no error.

Real use case 3: wait until the user stops typing

When a user types in a search box, you do not want to search after every single letter. That would send too many requests. A better idea: wait until the user pauses. Every new letter cancels the old timer and starts a fresh one:

const searchInput = document.getElementById("search");
let searchId;   // declared outside, so every key press can see it

searchInput.addEventListener("input", function () {
  clearTimeout(searchId);   // cancel the previous timer

  searchId = setTimeout(function () {
    console.log("Searching for: " + searchInput.value);
  }, 500);
});

If the user types j, ja, jav quickly, only the last timer is allowed to finish, so only one search happens. Try it in your head with the simulated version below:

let timerId;

function onType(text) {
  clearTimeout(timerId);
  timerId = setTimeout(() => console.log("Searching for: " + text), 300);
}

setTimeout(() => onType("j"), 0);
setTimeout(() => onType("ja"), 100);
setTimeout(() => onType("jav"), 200);
setTimeout(() => onType("java"), 700);

Output:

Searching for: jav
Searching for: java

Searches for j and ja never happened, because each was cancelled by the next key press. This clever pattern has a name, debounce, and you will meet it again in the performance lessons.

setInterval: repeat again and again

setInterval has the same shape as setTimeout. The difference is that it does not stop after one run. It runs your function every time the delay passes, until you cancel it:

setInterval(function, delay);
let count = 0;

const id = setInterval(() => {
  count++;
  console.log("Tick", count);

  if (count === 3) {
    clearInterval(id);   // stop the repeating alarm
    console.log("Stopped");
  }
}, 1000);

Output (one line every second):

Tick 1
Tick 2
Tick 3
Stopped

This is very important: a setInterval never stops on its own. If you do not call clearInterval, it keeps running for as long as the page is open. Always plan how and when your timer will stop.

Real use case 4: a live clock

In the dates lesson you learned how to read the current time. Now you can keep it fresh by running the same code every second:

const clock = document.getElementById("clock");

function showTime() {
  clock.textContent = new Date().toLocaleTimeString();
}

showTime();                  // show the time immediately
setInterval(showTime, 1000); // then update every second

Notice we call showTime() once before the interval. Without that line, the clock would stay empty for the first second, because setInterval waits for one full delay before its first run.

Real use case 5: “Resend OTP in 30s”

Almost every login or payment page has this. The button is disabled, a countdown runs, and when it reaches zero the button works again:

const resendButton = document.getElementById("resend");

let secondsLeft = 30;
resendButton.disabled = true;
resendButton.textContent = "Resend OTP in " + secondsLeft + "s";

const countdownId = setInterval(function () {
  secondsLeft--;

  if (secondsLeft === 0) {
    clearInterval(countdownId);
    resendButton.disabled = false;
    resendButton.textContent = "Resend OTP";
  } else {
    resendButton.textContent = "Resend OTP in " + secondsLeft + "s";
  }
}, 1000);

Here is the same logic with 5 seconds, printed in the console:

let secondsLeft = 5;
console.log("Resend OTP in " + secondsLeft + "s");

const timerId = setInterval(function () {
  secondsLeft--;

  if (secondsLeft === 0) {
    clearInterval(timerId);
    console.log("You can resend the OTP now");
  } else {
    console.log("Resend OTP in " + secondsLeft + "s");
  }
}, 1000);

Output (one line every second):

Resend OTP in 5s
Resend OTP in 4s
Resend OTP in 3s
Resend OTP in 2s
Resend OTP in 1s
You can resend the OTP now

Real use case 6: a rotating banner

Banners and sliders change their text or image every few seconds. The % operator from the operators lesson makes the list loop back to the start:

const quotes = ["Practice daily", "Read the error", "Small steps win"];
let index = 0;

const banner = document.getElementById("banner");
banner.textContent = quotes[index];

setInterval(function () {
  index = (index + 1) % quotes.length;   // 0, 1, 2, 0, 1, 2, ...
  banner.textContent = quotes[index];
}, 3000);

When index is 2 and you add 1, you get 3, and 3 % 3 is 0, so you are back at the first quote.

The most common bug: starting a timer twice

Imagine a Start button that creates a setInterval. What if the user clicks it twice?

let count = 0;
let id;

function start() {
  id = setInterval(() => count++, 100);
}

start();
start();   // clicked twice!

Now two intervals are running. The counter goes up twice as fast. Worse, id now holds only the second timer’s ID, so the first timer can never be cancelled. It keeps running until the page is closed. In a test of this code, after about half a second the counter was at 10 instead of 5.

The fix is to remember whether a timer is already running:

let count = 0;
let id = null;   // null means "no timer running"

function start() {
  if (id !== null) return;   // already running, do nothing
  id = setInterval(() => count++, 100);
}

function stop() {
  clearInterval(id);
  id = null;                 // forget the old timer
}

The same test now gives 5. Three habits will save you from most timer bugs:

  1. Declare the ID variable outside your functions, so both start and stop can see it (remember scope).
  2. Check the ID before starting a new timer.
  3. Set the ID back to null after you clear it.

Timers inside objects

In the this lesson, one of the challenges was to build a timer object. Now you have everything you need. The arrow function inside setInterval keeps the this of the start method, so it can reach this.seconds:

const timer = {
  seconds: 0,
  id: null,

  start() {
    this.id = setInterval(() => {
      this.seconds++;
      console.log("seconds:", this.seconds);
    }, 1000);
  },

  stop() {
    clearInterval(this.id);
    console.log("stopped at", this.seconds);
  }
};

timer.start();
setTimeout(() => timer.stop(), 3500);

Output:

seconds: 1
seconds: 2
seconds: 3
stopped at 3

If you write a regular function () {} inside setInterval, this is lost, as you saw in the this lesson. Use an arrow function here.

Running steps one after another

Sometimes you want steps to happen in a sequence: step 1 now, step 2 after a while, step 3 after a longer while.

Different delays

Because each setTimeout runs on its own, you can give each one a different delay. A let loop makes this short:

for (let i = 1; i <= 3; i++) {
  setTimeout(() => console.log("Step " + i), i * 1000);
}

Output:

Step 1
Step 2
Step 3

(One second apart.) All three timers start at the same moment, only their delays differ. Notice that we used let, so each callback remembers its own i, just like in the closures lesson.

Chained timers: a timer that starts the next timer

Another style is to start the next timer from inside the previous one. This is useful when the delay should change each time, for example when you retry something and wait longer after each failure:

let attempt = 1;

function tryAgain() {
  console.log("Attempt " + attempt);

  if (attempt < 3) {
    attempt++;
    setTimeout(tryAgain, attempt * 1000);   // wait longer each time
  } else {
    console.log("Giving up");
  }
}

tryAgain();

Output:

Attempt 1
Attempt 2
Attempt 3
Giving up

Attempt 2 starts after 2 seconds, and attempt 3 after 3 more seconds. A single setInterval cannot do this, because its delay is fixed. A chain of setTimeout calls also makes sure the next round starts only after the current one has finished its work.

Tip: Chained timers are easy for 2 or 3 steps. If you need many steps that depend on each other, the code becomes a deep pyramid of callbacks. This is the “callback hell” problem, and Promises, which come later in this section, solve it.

Timers are not exact

A timer delay is the minimum wait, not the exact time. You saw in the last lesson that a busy JavaScript makes a timer late. There is one more thing: browsers slow down timers in tabs that are in the background, to save battery. So an interval set to 1 second may run less often when the user is on another tab.

This means you should not count time by adding 1 on every tick if you need accuracy, such as in a stopwatch. Instead, compare the current time with the start time using Date.now(). The interval is only used to refresh the screen:

const startTime = Date.now();

const id = setInterval(() => {
  const elapsed = Math.floor((Date.now() - startTime) / 1000);
  console.log("Seconds passed:", elapsed);
}, 1000);

Even if some ticks are late, elapsed is always correct, because it comes from the real clock.

Quick comparison

setTimeout setInterval Chained setTimeout
Runs Once Again and again Again and again
Delay between runs Not applicable Fixed Can change every time
Stops by Finishing (or clearTimeout) Only clearInterval When you stop calling it
Good for Auto-hide, delay, undo, debounce Clock, countdown, slider Retry with growing wait

Common mistakes

  • Calling the function instead of passing it. setTimeout(greet(), 1000) runs greet now. Write setTimeout(greet, 1000).
  • Mixing up seconds and milliseconds. setTimeout(fn, 2) waits 2 milliseconds, not 2 seconds. Write 2000.
  • Never clearing an interval. It runs forever. Always plan when to call clearInterval.
  • Starting the same interval twice. Check that the timer ID is null before creating a new one.
  • Losing the timer ID. If you declare the ID inside a function with let or const, other functions cannot see it, so you cannot cancel the timer. Declare it outside.
  • Expecting exact timing. Delays are minimums. Use Date.now() for accurate stopwatches.
  • Using var in a loop with timers. All callbacks share one variable. Use let, as you learned in the closures lesson.
  • Losing this inside a timer. Passing obj.method directly to setTimeout loses this. Use an arrow function wrapper.
  • Doing very long work inside the callback. A slow callback blocks the page, exactly like in the last lesson.

Practice

  1. Print Start, then Middle after 2 seconds, then End right after Start. Predict the order before you run it.
  2. Create a function sayHi(name) and use setTimeout to call it after 1 second with the name "Aman", passing the name as an extra argument.
  3. Write a setInterval that prints the numbers 1 to 5, one per second, and then stops itself.
  4. In the practice editor, click Start twice quickly. Why does the counter not speed up? Then remove the line if (intervalId !== null) return;, run it again, and explain what changes.
  5. Build a button that shows Copied! for 2 seconds and then goes back to its normal text. What happens if the user clicks again before the 2 seconds are over? Fix it using clearTimeout.
  6. Build a live clock that shows the current time and updates every second. Remember to show the time immediately and not only after the first second.
  7. Challenge: Build an OTP countdown from 10 seconds. The button should be disabled during the countdown and should say Resend OTP when it ends.
  8. Challenge: Build a stopwatch with Start, Stop and Reset buttons. Use Date.now() so the time stays correct even when the tab is in the background.
  9. Challenge: Write a function retry(times) that prints Attempt 1, Attempt 2, and so on, waiting one second longer before each new attempt, and stops after times attempts.

Recap

  • setTimeout(fn, ms) runs a function once after a delay. setInterval(fn, ms) runs it again and again.
  • The delay is in milliseconds: 1000 is one second.
  • Pass the function itself (greet), not its result (greet()). Extra values after the delay are sent to the function.
  • Both timer functions return a timer ID. Give it to clearTimeout or clearInterval to cancel the timer.
  • A setInterval never stops by itself. Always plan how it will stop, and never start the same one twice.
  • Declare timer IDs outside your functions and reset them to null after clearing.
  • A delay is a minimum. Busy JavaScript and background tabs can make timers late, so use Date.now() when you need accurate time.
  • Real uses: auto-hide messages, undo, search delay (debounce), live clocks, OTP countdowns, sliders and retries.

Timers use callbacks, and they are only one kind of asynchronous callback. In the next lesson you will see asynchronous callbacks in general, the patterns people use with them, and why they become hard to manage. That sets the stage for the event loop and for Promises.

If anything here felt unclear, revisit the synchronous vs asynchronous lesson and the callbacks lesson.

Frequently asked questions

What is the difference between setTimeout and setInterval?

setTimeout runs a function once after a delay. setInterval runs it again and again at that interval until you stop it with clearInterval. Both return an ID that you pass to the matching clear function.

Why is my setTimeout not exactly on time?

The delay is a minimum, not a guarantee. The callback waits until the main thread is free, so a busy page can run it later. Browsers may also slow timers in background tabs.

How do I stop a setInterval?

Save the ID that it returns, as in const id = setInterval(fn, 1000), and call clearInterval(id) when you are done. Forgetting to stop an interval keeps it running and can cause bugs and memory use.

Does setTimeout(fn, 0) run immediately?

No. It runs the function after the current code and pending microtasks finish, as soon as the main thread is free. It is a way to say “run this after everything else that is ready right now”.

Why should I prefer setTimeout over setInterval for repeating tasks?

With setInterval, a slow task can pile up calls. A setTimeout that schedules the next call after each run guarantees a gap between runs. For animation, requestAnimationFrame is better still.

See also: The Event Loop, Asynchronous Callbacks, Promises, JavaScript Cheat Sheet