JavaScript Window setInterval() Method

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Repeating timer

What You’ll Learn

The setInterval() method runs a function on a repeating timer. This tutorial covers syntax, interval IDs, delay in milliseconds, passing arguments, stopping with clearInterval(), comparison with setTimeout(), five examples, and cleanup habits.

01

Syntax

setInterval(fn, ms)

02

Repeats

Until cleared

03

ID

Save return value

04

Stop

clearInterval(id)

05

vs timeout

Once vs loop

06

Args

Extra parameters

Introduction

Many features need code to run again and again: live clocks, countdown timers, slideshows, and polling for new messages. JavaScript timers handle this without blocking the page. The setInterval() method schedules a callback on the browser’s event loop so your UI stays responsive between ticks.

Each call returns an interval ID. Keep that ID so you can stop the loop with clearInterval() when the user clicks Stop or navigates away. Forgetting to clear intervals is a common source of bugs and wasted battery life.

Understanding the setInterval() Method

setInterval(callback, delayMs, arg1, arg2, ...) registers callback to run every delayMs milliseconds (minimum ~4ms in modern browsers, but use sensible values like 1000 for a one-second clock). It returns a numeric ID immediately—the first run happens after the delay, not instantly.

Timers are asynchronous: code after setInterval() runs right away while the callback waits for the clock. Multiple intervals can run at the same time; each has its own ID.

💡
Beginner Tip

Always assign the return value: const id = setInterval(tick, 1000). Without the ID you cannot stop that specific timer with clearInterval(id).

📝 Syntax

General form of setInterval():

JavaScript
const intervalId = setInterval(callback, delayMs, param1, param2);

// shorthand (same in browsers):
const id = setInterval(tick, 1000);

Parameters

  • callback — function to execute on each tick. Can be a function reference or inline function.
  • delayMs — milliseconds between calls. Use 1000 for one second.
  • param1, param2, ... (optional) — extra values passed to callback.

Return value

  • A numeric interval ID. Pass it to clearInterval() to cancel.

Related APIs

  • clearInterval(id) — stop a repeating timer.
  • setTimeout(fn, ms) — run once after a delay.
  • clearTimeout(id) — cancel a one-shot timer.
  • requestAnimationFrame(fn) — smooth animation frames.

⚡ Quick Reference

TopicDetail
Start repeating timerconst id = setInterval(fn, ms)
Every 1 secondsetInterval(fn, 1000)
Stop timerclearInterval(id)
Pass argumentssetInterval(fn, 2000, "Hi")
Run oncesetTimeout(fn, ms) instead
Animation framesrequestAnimationFrame

📋 setInterval() vs setTimeout() vs clearInterval()

Start repeating work, schedule a single delay, or stop a loop.

setInterval
setInterval(fn, 1000)

Repeats every 1s

setTimeout
setTimeout(fn, 1000)

Runs once after 1s

clearInterval
clearInterval(id)

Stop the loop

rAF
requestAnimationFrame

Smooth visuals

Examples Gallery

Use the Try-it links to start timers in the browser. Watch the output update on each tick, then stop intervals when done.

📚 Getting Started

Log a message every two seconds.

Example 1 — Basic Repeating Callback

Run a named function on a fixed schedule.

JavaScript
function logMessage() {
  console.log("Interval elapsed — executing function…");
}

const intervalId = setInterval(logMessage, 2000);
Try It Yourself

How It Works

The callback runs repeatedly until you call clearInterval(intervalId) or leave the page. The first execution waits 2000ms.

📈 Practical Patterns

Clocks, counters, arguments, and bounded loops.

Example 2 — Update a Live Clock Every Second

Refresh DOM text with the current time.

JavaScript
function updateClock() {
  const now = new Date().toLocaleTimeString();
  document.getElementById("clock").textContent = now;
}

updateClock(); // show immediately
setInterval(updateClock, 1000);
Try It Yourself

How It Works

Calling updateClock() once before the interval avoids a one-second blank on load. Store the interval ID if the clock should stop when a modal closes.

Example 3 — Start and Stop with Buttons

Prevent duplicate intervals by clearing before starting again.

JavaScript
let intervalId = null;
let count = 0;

document.getElementById("startBtn").onclick = function () {
  if (intervalId !== null) return;
  intervalId = setInterval(function () {
    count++;
    document.getElementById("count").textContent = count;
  }, 500);
};

document.getElementById("stopBtn").onclick = function () {
  clearInterval(intervalId);
  intervalId = null;
};
Try It Yourself

How It Works

Clicking Start twice without this guard would create two intervals and double the speed. Set intervalId = null after clearing so you can detect a stopped state.

Example 4 — Pass Arguments to the Callback

Extra parameters after the delay are forwarded to your function.

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

setInterval(greet, 3000, "Alex");
Try It Yourself

How It Works

Arrow functions are another option: setInterval(() => greet("Alex"), 3000). Both styles avoid global variables for the greeting name.

Example 5 — Stop After a Fixed Number of Ticks

Clear the interval from inside the callback when a limit is reached.

JavaScript
let ticks = 0;
const maxTicks = 5;

const intervalId = setInterval(function () {
  ticks++;
  console.log("Tick " + ticks);

  if (ticks >= maxTicks) {
    clearInterval(intervalId);
    console.log("Done — interval cleared.");
  }
}, 1000);
Try It Yourself

How It Works

Countdowns and limited polls often self-clear. Alternatively, use setTimeout chained recursively when you need variable delays between runs.

🚀 Common Use Cases

  • Live clocks and countdowns — update time display every second.
  • Image slideshows — advance slides on a timer (clear when hidden).
  • Polling APIs — fetch new data every N seconds (prefer WebSockets when possible).
  • Progress indicators — simulate loading steps in tutorials.
  • Simple animations — move elements in small steps (consider requestAnimationFrame for smooth motion).
  • Session timeouts — warn users before auto-logout.

🧠 What Happens When You Call setInterval()

1

Register timer

Browser stores callback + delay and returns an interval ID immediately.

Start
2

Script continues

Code after setInterval runs without waiting for the first tick.

Async
3

Callback fires

After delayMs, the function runs on the event loop—then again every delay.

Repeat
4

Until cleared

clearInterval(id) stops future ticks. Page close also stops timers.

📝 Notes

  • Delay is minimum time, not exact—busy tabs may tick late.
  • Do not start a second interval without clearing the first—ticks will stack.
  • Long-running callback code can overlap the next tick if it exceeds the delay.
  • Background tabs may throttle timers to save battery (intervals > 1000ms are safer).
  • In Node.js, setInterval works similarly but IDs differ from browser numbers.
  • For visual animation at 60fps, prefer requestAnimationFrame over setInterval(fn, 16).

Browser Support

setInterval() has been supported since the earliest JavaScript timer APIs in browsers and matches universal runtime support.

Universal · Standard API

setInterval()

Supported in Chrome, Firefox, Safari, Edge, Opera, Node.js, and WebViews. Works alongside clearInterval() everywhere timers exist.

100% Universal support
Google Chrome All versions · Desktop & Mobile
Full support
Mozilla Firefox All versions · Desktop & Mobile
Full support
Apple Safari All versions · macOS & iOS
Full support
Microsoft Edge All versions · Chromium & Legacy
Full support
Internet Explorer IE 6+ · Legacy environments
Full support
Opera All modern versions
Full support
setInterval() Universal

Bottom line: Safe to use in any JavaScript environment with timers. Focus on storing IDs and calling clearInterval()—not polyfills.

Conclusion

setInterval() repeats a callback every N milliseconds and returns an ID for cleanup. It powers clocks, slideshows, and polling—but only when you remember to stop timers you no longer need.

Pair it with clearInterval(), compare with setTimeout() for one-shot work, and reach for requestAnimationFrame() when smooth visuals matter most.

💡 Best Practices

✅ Do

  • Save every setInterval return value in a variable
  • Call clearInterval(id) when done
  • Guard against double-starting the same interval
  • Use sensible delays (1000ms for clocks, not 1ms busy loops)
  • Clear intervals when components unmount in SPAs

❌ Don’t

  • Leave intervals running after the UI is removed
  • Stack multiple intervals on the same task
  • Assume ticks are perfectly precise to the millisecond
  • Run heavy work every few ms without throttling
  • Use setInterval for all animation—try rAF first

Key Takeaways

Knowledge Unlocked

Five things to remember about setInterval()

Your foundation for repeating timers in JavaScript.

5
Core concepts
🔄 02

Repeats

Until cleared.

Loop
🔖 03

ID

Store return.

Handle
🛑 04

Stop

clearInterval.

Cleanup
05

vs timeout

Once vs repeat.

Compare

❓ Frequently Asked Questions

It schedules a function to run repeatedly after a fixed delay in milliseconds. Each call to setInterval() returns a numeric interval ID you can pass to clearInterval() to stop the loop.
A numeric interval ID (timer handle). Store it in a variable—e.g. const id = setInterval(tick, 1000)—so you can stop that specific interval later with clearInterval(id).
setTimeout(fn, ms) runs once after the delay. setInterval(fn, ms) runs again and again until you call clearInterval() or close the page. Use setTimeout for one-shot delays; setInterval for repeating tasks.
Yes. Extra arguments after the delay are forwarded to your function: setInterval(greet, 2000, "Alex"). Alternatively, use an arrow function: setInterval(() => greet("Alex"), 2000).
A running interval keeps firing forever, wasting CPU and battery. Clear it when the user navigates away, when a countdown finishes, or when the UI no longer needs updates.
For 60fps motion, requestAnimationFrame() is usually better—it syncs with the screen refresh. setInterval() is fine for clocks, polling, and simple step updates every second or more.
Did you know?

Browsers share one timer ID pool for setTimeout and setInterval, but you should still use clearInterval for intervals and clearTimeout for timeouts—matching the API that created the timer keeps code readable.

Continue to setTimeout()

Learn how to run code once after a delay with the window.setTimeout() method.

setTimeout() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful