简体   繁体   中英

How to stop interval on function?

I got function, which is interval. And I need to stop it when it finishes. here is the code:

 function cut() {
    setInterval(function() {
       timer()
    }, 1000);
 }


 function timer() {

    seconds = seconds - 1;
    document.getElementById("timer1").innerHTML = minutes + ":" + seconds;
    if (seconds < 10) {
       document.getElementById("timer1").innerHTML = minutes + ":" + "0" + seconds
    }
    if (seconds <= 0) {
       clearInterval("cut()");


       //another code to be executed
    }
 }

can I use this clearInterval for function at all? or there is another solution for doing that?

Thanks :)

You have to keep a reference to the handle returned from setInterval() and then pass it to clearInterval() like so:



function cut() {
    setInterval(timer, 1000);
}

function timer() {
    seconds = seconds - 1;
    var timer = document.getElementById("timer1");
    timer.innerHTML = minutes + ":" + seconds;
    if (seconds < 10) {
        timer.innerHTML = minutes + ":" + "0" + seconds
    }
    if (seconds <= 0) {
        clearInterval();
        //another code to be executed
    }
}

Save your interval in a variable:

var myInterval= setInterval(function(){//your code here},1000);

//whenever you want to end the interval, call:
clearInterval(myInterval);

Thus, your cut() function should changed to this:

var myInterval;
function cut() {
    myInterval = setInterval(function() {timer()}, 1000);
}
function clear(){
    clearInterval(myInterval);
}

// the rest of your code:
function timer() {
    seconds = seconds - 1;
    document.getElementById("timer1").innerHTML = minutes + ":" + seconds;
    if (seconds < 10) {
        document.getElementById("timer1").innerHTML = minutes + ":" + "0" + seconds
    }
    if (seconds <= 0) {
       clear();

       //another code to be executed
    }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM