JavaScript clearInterval() Method

Beginner
⏱️ 7 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Timers

What You’ll Learn

The clearInterval() method stops a repeating timer started with setInterval(). This tutorial covers syntax, interval IDs, five practical examples, comparison with clearTimeout(), and cleanup habits every beginner should adopt.

01

Syntax

clearInterval(id)

02

Stops

setInterval() loops

03

Needs ID

Return value stored

04

vs timeout

clearTimeout()

05

Cleanup

Prevent leaks

06

Return

undefined

Introduction

setInterval() runs a function again and again after a fixed delay. That is perfect for clocks, slideshows, or polling—but only while you still need repetition. When the job is done, call clearInterval() with the timer ID to shut it off.

Without clearing, the callback keeps firing in the background, updating the DOM, hitting APIs, or wasting battery. Learning clearInterval() is essential timer hygiene in browser JavaScript and Node.js alike.

Understanding the clearInterval() Method

When you call setInterval(fn, delay), the browser returns a numeric interval ID. Pass that ID to clearInterval(id) and the scheduled repeats stop. The function does not run one last time automatically—it simply will not be called again.

Think of the ID as a handle on a repeating alarm. You can clear it from a button click, after a condition becomes true, when navigating away, or when a one-shot setTimeout() decides enough time has passed.

💡
Beginner Tip

Always save the return value: const id = setInterval(tick, 1000). Without the ID you cannot reliably stop that specific interval later.

📝 Syntax

General form of clearInterval():

JavaScript
clearInterval(intervalId);
// same on window:
window.clearInterval(intervalId);

Parameters

  • intervalId — the value returned by setInterval(). If the ID is invalid or already cleared, the call is ignored.

Return value

  • undefined.

Common patterns

  • clearInterval(timerId) inside a Stop button handler.
  • if (count >= max) clearInterval(timerId) when a limit is reached.
  • clearInterval(timerId); timerId = null; after cleanup to avoid double-use.
  • setTimeout(() => clearInterval(id), 5000) to auto-stop after five seconds.

⚡ Quick Reference

TopicDetail
Starts withsetInterval(fn, ms)
Stops withclearInterval(id)
One-shot timerUse clearTimeout() instead
ID typeNumber (browser) or object (Node)
Double clearSafe — second call is a no-op
Return valueundefined

📋 clearInterval() vs clearTimeout()

Match the clear function to the timer that created it. Intervals repeat; timeouts run once.

Repeating
setInterval

Clear with clearInterval

One-shot
setTimeout

Clear with clearTimeout

Store ID
const id = …

Required for both

After clear
id = null

Optional hygiene

Examples Gallery

Use the Try-it links for live counters and stop buttons. In DevTools, watch the console or on-page output stop updating once clearInterval() runs.

📚 Getting Started

Start an interval, then clear it after time passes or on user action.

Example 1 — Stop an Interval After Five Seconds

Log a message every second, then use setTimeout plus clearInterval to stop.

JavaScript
const intervalId = setInterval(function () {
  console.log("Tick…");
}, 1000);

setTimeout(function () {
  clearInterval(intervalId);
  console.log("Interval cleared after 5 seconds.");
}, 5000);
Try It Yourself

How It Works

The interval fires about once per second until the five-second timeout runs clearInterval. No further ticks appear after that line executes.

📈 Practical Patterns

User controls, conditional stops, cleanup, and UI updates.

Example 2 — Stop on Button Click

Let the user halt a running counter with a Stop button.

JavaScript
let count = 0;
const output = document.getElementById("count");

const intervalId = setInterval(function () {
  count++;
  output.textContent = count;
}, 500);

document.getElementById("stopBtn").addEventListener("click", function () {
  clearInterval(intervalId);
  output.textContent = count + " — stopped";
});
Try It Yourself

How It Works

The click handler passes the stored interval ID to clearInterval. The counter freezes at its last value because no new interval callbacks are scheduled.

Example 3 — Stop When a Condition Is Met

Clear the interval inside the callback once a target count is reached.

JavaScript
let count = 0;
const max = 5;

const intervalId = setInterval(function () {
  count++;
  console.log("Count:", count);

  if (count >= max) {
    clearInterval(intervalId);
    console.log("Reached max — interval cleared.");
  }
}, 400);
Try It Yourself

How It Works

The fifth tick triggers clearInterval from inside the same callback. This self-stop pattern is common for countdowns and retry limits.

Example 4 — Clear and Null Out the ID

Prevent accidental double-starts by resetting the handle after cleanup.

JavaScript
let intervalId = setInterval(function () {
  console.log("Running…");
}, 800);

function stopTimer() {
  if (intervalId !== null) {
    clearInterval(intervalId);
    intervalId = null;
    console.log("Timer stopped and ID cleared.");
  }
}

stopTimer();
Try It Yourself

How It Works

Setting intervalId = null after clearing makes it obvious the timer is off. Guard clauses like if (intervalId !== null) help Start/Stop toggles stay predictable.

Example 5 — Simple Slideshow with Manual Stop

Rotate text every second until the user clicks Stop.

JavaScript
<p id="slide">Slide 1</p>
<button type="button" id="stopBtn">Stop slideshow</button>

<script>
  const slides = ["Slide 1", "Slide 2", "Slide 3"];
  let index = 0;

  const intervalId = setInterval(function () {
    index = (index + 1) % slides.length;
    document.getElementById("slide").textContent = slides[index];
  }, 1000);

  document.getElementById("stopBtn").onclick = function () {
    clearInterval(intervalId);
  };
</script>
Try It Yourself

How It Works

The interval updates the paragraph on a loop. clearInterval on button click ends the rotation without removing the element from the page.

🚀 Common Use Cases

  • Clocks and counters — stop updating when the user leaves the page section.
  • Slideshows / carousels — halt auto-advance on Stop or when hovered.
  • Polling APIs — cease requests after data arrives or on error.
  • Games and animations — pause loops when the game ends.
  • Progress indicators — stop fake loading bars at 100%.
  • SPA cleanup — clear intervals when a component unmounts or route changes.

🧠 What Happens When You Call clearInterval()

1

Pass interval ID

Provide the handle returned by setInterval().

ID
2

Remove schedule

The runtime cancels future invocations of that interval.

Cancel
3

In-flight tick

A callback already running finishes; the next tick will not start.

Note
4

Timer off

Returns undefined. Start a fresh setInterval() if you need to resume.

📝 Notes

  • clearInterval() and clearTimeout() share the same ID pool in browsers—still use the matching clear function for clarity.
  • Very short delays (0 ms) still queue on the event loop; clearing prevents backlog from growing.
  • In Node.js, clearInterval accepts the object returned by setInterval there.
  • Page unload destroys timers, but clear them earlier when navigating inside SPAs.
  • requestAnimationFrame loops need cancelAnimationFrame, not clearInterval.
  • Prefer one interval per feature—multiple overlapping intervals are harder to debug.

Browser Support

clearInterval() has been available since the earliest JavaScript timer APIs in browsers and matches setInterval() support everywhere.

Universal · Timer API

clearInterval()

Supported in Chrome, Firefox, Safari, Edge, Opera, Node.js, and WebViews. Works alongside setInterval() in every modern environment.

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
clearInterval() Universal

Bottom line: Safe to rely on in any JavaScript runtime that provides setInterval(). Focus on storing IDs and cleaning up—not polyfills.

Conclusion

clearInterval() is how you turn off repeating timers. Store the ID from setInterval(), clear when work is done, and null out handles when building Start/Stop controls.

Pair this lesson with setInterval() to start timers and clearTimeout() for one-shot delays.

💡 Best Practices

✅ Do

  • Save the return value of every setInterval()
  • Clear intervals when components unmount or pages change
  • Set the ID variable to null after clearing
  • Use one interval per repeating task when possible
  • Combine with conditions or buttons for predictable stops

❌ Don’t

  • Forget to clear polling loops after success
  • Call clearTimeout() on an interval ID by habit
  • Start duplicate intervals without clearing the old one
  • Assume the page reload will fix leaks in SPAs
  • Use intervals for smooth animation—prefer requestAnimationFrame

Key Takeaways

Knowledge Unlocked

Five things to remember about clearInterval()

Your foundation for stopping repeating timers in JavaScript.

5
Core concepts
🔄 02

Pair

Stops setInterval.

Match
📋 03

Store ID

Save return value.

Handle
04

Cleanup

Stop leaks.

Hygiene
05

Not timeout

Use clearTimeout for those.

Compare

❓ Frequently Asked Questions

It cancels a repeating timer created by setInterval(). After clearInterval(id) runs, that callback will not fire again unless you start a new setInterval().
The numeric interval ID returned by setInterval(). Store that ID in a variable so you can pass it to clearInterval() later.
clearInterval() stops repeating timers from setInterval(). clearTimeout() cancels a one-shot timer from setTimeout(). They are not interchangeable—use the matcher for the API that created the timer.
The second call is harmless. Once an interval is cleared, its ID no longer schedules work. Setting the variable to null after clearing helps avoid accidental reuse.
Both clearInterval(id) and window.clearInterval(id) work in browsers. clearInterval is a global function on the window object.
A running interval keeps firing, wasting CPU and battery. It can also update DOM nodes that were removed or cause memory leaks in long-lived single-page apps.
Did you know?

In browsers, setInterval(fn, 0) does not run infinitely fast—it queues callbacks as fast as the event loop allows. Clearing such an interval quickly is still important if the callback schedules heavy work each tick.

Continue to clearTimeout()

Learn how to cancel a one-shot delay created with setTimeout().

clearTimeout() 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