Skip to content

JavaScript setInterval stop | Example code

  • by

Use the clearInterval() method to stop JavaScript setInterval. The setInterval() returns an interval ID, which you can pass to clearInterval():

intervalId= setInterval(function, milliseconds);

Then you can stop the execution by calling clearInterval():


JavaScript setInterval stop

Simple example code.

<!DOCTYPE html>
  <p id="demo"></p>

  <button onclick="myStop()">Stop the time</button>

    const myInterval = setInterval(myTimer, 1000);

    function myTimer() {
      const date = new Date();
      document.getElementById("demo").innerHTML = date.toLocaleTimeString();

    function myStop() {



JavaScript setInterval stop

You can set a new variable and have it incremented by ++ (count up one) every time it runs, then I use a conditional statement to end it:

var intervalId = null;
var varCounter = 0;
var varName = function(){
     if(varCounter <= 10) {
          /* your code goes here */
     } else {

     intervalId = setInterval(varName, 10000);

Do comment if you have any doubts or suggestions on this JS set Interval topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *