如果间隔达到0,则停止计时器

时间:2016-02-15 07:55:13

标签: javascript php html

我需要停止计时器,如果它达到0.我需要在00.00停止倒计时并显示alert(countdown stopped)。现在它再次启动。需要在达到00.00后停止

function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    setInterval(function () {
        minutes = parseInt(timer / 60, 10)
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.textContent = minutes + ":" + seconds;

        if (--timer < 0) {
            timer = duration;
        }
    }, 1000);
}

window.onload = function () {
    var fiveMinutes = 60 * .05,
        display = document.querySelector('#time');
    startTimer(fiveMinutes, display);
};
<body>
    <div>Registration closes in <span id="time">start</span> minutes!</div>
</body>

2 个答案:

答案 0 :(得分:0)

请在代码段中使用clearInterval。

&#13;
&#13;
function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    var __timer = setInterval(function () {
        minutes = parseInt(timer / 60, 10)
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.textContent = minutes + ":" + seconds;

        if (--timer < 0) {
            clearInterval(__timer);
            timer = duration;
        }
    }, 1000);
}

window.onload = function () {
    var fiveMinutes = 60 * .05,
        display = document.querySelector('#time');
    startTimer(fiveMinutes, display);
};
&#13;
<body>
    <div>Registration closes in <span id="time">start</span> minutes!</div>
</body>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

Orr你可以包装这行代码

if (--timer < 0) {
        timer = duration;
    }

  if (display.textContent != "0:00") {

            if (--timer < 0) {
                timer = duration;
            }
        }