仍然在clearInterval()

时间:2015-11-17 11:57:59

标签: javascript jquery setinterval clearinterval

我在点击时调用了setInterval函数,但在使用End Timer按钮清除它之后,它继续运行。它是一个倒计时钟,所以我想制作2个按钮,一个复位按钮和一个结束按钮。两者都会做同样的事情,除了结束将使得分钟和秒值都为0并且重置将使得分钟25。我是javascript的新手所以我假设clearInterval()将终止setInterval()函数并且不允许它被调用,直到再次点击相应的按钮。

var minCount = 25;          
var count = 60;

$("#begin").click(function timer(){
    var count = 60;
    minCount = minCount - 1;

    var counter = setInterval(function(){
        document.getElementById("min").innerHTML = minCount;
        count -= 1;
        document.getElementById("sec").innerHTML = count;

        if(count < 10){
            document.getElementById("sec").innerHTML = "0"+count;
            if(count == 0){
                clearInterval(counter);
                document.getElementById("min").innerHTML = minCount;
                document.getElementById("sec").innerHTML = count+"0";

                timer();
            }
        }
    },1000)
});

$("#end").click(function(){
    clearInterval(timer);
    document.getElementById("min").innerHTML = "00";
    document.getElementById("sec").innerHTML = "00";        
});

2 个答案:

答案 0 :(得分:1)

你为什么打电话给clearInterval(timer)

您需要传递counter间隔。

但是,你是在&#34;开始点击&#34;范围,并在&#34;结束点击&#34;范围不会起作用。尝试将其提取到一个通用范围(例如,在minCount和count之后)并在clearInterval上使用它。

Check this jsfiddle

答案 1 :(得分:1)

您需要将间隔定义为变量。 见下面的例子:

var minCount = 25;
var count = 60;
var counter;


$("#begin").click(function timer() {
    var count = 60;
    minCount = minCount - 1;

    counter = setInterval(function () {
        document.getElementById("min").innerHTML = minCount;
        count -= 1;
        document.getElementById("sec").innerHTML = count;

        if (count < 10) {
            document.getElementById("sec").innerHTML = "0" + count;
            if (count == 0) {
                clearInterval(counter);
                document.getElementById("min").innerHTML = minCount;
                document.getElementById("sec").innerHTML = count + "0";

                timer();
            }
        }

    }, 1000)
});


$("#end").click(function () {
    clearInterval(counter);
    document.getElementById("min").innerHTML = "00";
    document.getElementById("sec").innerHTML = "00";

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="begin">Begin</button>
<button id="end">End</button>
<div id="min">0</div>
<div id="sec">0</div>