Javascript setInterval未被清除

时间:2014-03-06 04:16:59

标签: javascript

由于某种原因,未从以下代码中清除计时器:

var countdown = function() {
    if (!interval || !countdownOngoing) {
        countdownOngoing = true;
        interval = setInterval(countdownFunction, 1000);
    }
};

function countdownFunction() {
    if(seconds == 0) {
        if (minutes == 0) {
            countdownOngoing = false;
            clearInterval(interval);
            return;
        } else {
            minutes--;
            seconds = 60;
        }
    }

    seconds--;
}

setInterval在clearInterval之后仍然有效。我错过了什么?

1 个答案:

答案 0 :(得分:0)

假设它看起来像我下面写的那样,它可能是你的分钟+秒逻辑。

var interval = null,
countDownGoing = false;

function countdown() {
    if(!interval || !countDownGoing) {
         interval = setInterval(countdownFunction, 1 * 1000);   
        countDownGoing = true;
    }
}

countdown()

setTimeout(function() {
    countDownGoing = false;
}, 5 * 1000);


function countdownFunction() {
    if(!countDownGoing) {
        clearInterval(interval);
    } else {
        alert(countDownGoing);
    }
}