[Solved-6 Solutions] Stop setInterval call in JavaScript - javascript tutorial



Problem:

Is it possible to stop setinterval call in javascript ?

Solution 1:

The setInterval() method will execute the "myTimer" function once every 1 second. Use clearInterval() to stop the time.

<!DOCTYPE html>
<html>
<body>
<p>A script on this page starts this clock:</p>
<p id="demo"></p>
<button onclick="myStopFunction()">Stop time</button>
<script>
var myVar = setInterval(myTimer, 1000);
function myTimer() {
    var d = new Date();
    var t = d.toLocaleTimeString();
    document.getElementById("demo").innerHTML = t;
}

function myStopFunction() {
    clearInterval(myVar);
}
</script>
</body>
</html>

Solution 2:

To start displaying current time by using toTimeString() function. We will keep display part inside a function disp(). Using setInterval method we will call disp() function in every one second ( 1000 millisecond ).

<html>
    <head>
    <title>Page Title here</title>
    <script language=javascript>
        function to_start(){
            tm=window.setInterval('disp()',1000);
        }
        function to_stop(){
            window.clearInterval(tm);
        }
        function disp(){
            var dt= new Date();
            var str=dt.toTimeString()
            document.getElementById('n1').value=str;
        }
        </script>
    </head>
    <body>
        <input type=text id=n1>
        <input type="button" name="btn" value="Start" onclick="to_start()" ;>
        <input type="button" name="btn" value="Stop" onclick="to_stop()" ;>
    </body>
</html>

Read Also

Angular $Interval.

Solution 3:

An setInterval() returns an interval ID, which you can pass to clearInterval():

var refreshIntervalId = setInterval(fname, 10000);
/* later */
clearInterval(refreshIntervalId);

Solution 4:

We can assign the value of setInterval to a variable, you can useclearInterval to stop it.

var myTimer = setInterval(...);
clearInterval(myTimer);

Solution 5:

We can set a new variable and incremented by ++ every time it runs.

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

$(document).ready(function(){
     intervalId = setInterval(varName, 10000);
});

Solution 6:

The simple way is to use the attribute of a DOM object. If the reload is started by a start/stop button, you can use the button itself. Don’t use "scope-less" variables.

<a onclick="start(this);">Start</a>

<script>
function start(m)
{
    if (m.interval)
    {
        clearInterval(m.interval);
        m.innerHTML='Start';
    } else 
    {
        m.interval=setInterval(function()
        {
          //refresh here
        },10000);
        m.innerHTML='Stop';
    }
}
</script>


Related Searches to Stop setInterval call in JavaScript - javascript tutorial