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


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>
<p>A script on this page starts this clock:</p>
<p id="demo"></p>
<button onclick="myStopFunction()">Stop time</button>
var myVar = setInterval(myTimer, 1000);
function myTimer() {
    var d = new Date();
    var t = d.toLocaleTimeString();
    document.getElementById("demo").innerHTML = t;

function myStopFunction() {

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 ).

    <title>Page Title here</title>
    <script language=javascript>
        function to_start(){
        function to_stop(){
        function disp(){
            var dt= new Date();
            var str=dt.toTimeString()
        <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()" ;>

Read Also

Angular $Interval.

Solution 3:

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

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

Solution 4:

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

var myTimer = setInterval(...);

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) {
          /* your code goes here */
     } else {

     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>

function start(m)
    if (m.interval)
    } else 
          //refresh here

Related Searches to Stop setInterval call in JavaScript - javascript tutorial