如何停止功能间隔?

时间:2014-01-02 18:49:57

标签: javascript html

我得到了功能,这是间隔。而且我需要在它结束时停止它。这是代码:

 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
    }
 }

我可以使用这个clearInterval来完成这项功能吗?或者还有另一种解决办法吗?

谢谢:)

2 个答案:

答案 0 :(得分:3)

您必须保留对setInterval()返回的句柄的引用,然后将其传递给clearInterval(),如下所示:

var cutHandle;

function cut() {
    cutHandle = 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(cutHandle);
        //another code to be executed
    }
}

答案 1 :(得分:2)

将您的间隔保存在变量中:

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

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

因此,你的cut()函数应改为:

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
    }
 }