如何暂停/停止计时器?

时间:2013-12-31 04:29:30

标签: javascript button timer

我有一个计时器,但我想添加一个“STOP”按钮或链接,它将冻结计时器。怎么样?

HTML:

TIME LEFT: <font size="5" color='#F7D358'><span id='timer_div'></span></font>

JAVASCRIPT:

var seconds_left = 60;
var interval = setInterval(function() {
    document.getElementById('timer_div').innerHTML = --seconds_left;

    if (seconds_left <= 0)
    {
        document.getElementById('timer_div').innerHTML = '...';
        clearInterval(interval);
    }
}, 1000);

样本: http://jsfiddle.net/wa4ms/

5 个答案:

答案 0 :(得分:1)

只需使用此

即可
<input type="button" value="STOP" onclick="clearInterval(interval);" />

答案 1 :(得分:0)

这里至少是一个关于如何停止运行功能(计时器)的例子:

http://www.w3schools.com/js/tryit.asp?filename=tryjs_setinterval3

答案 2 :(得分:0)

HTML:

TIME LEFT: <font size="5" color='#F7D358'><span id='timer_div'></span></font>
<input type="button" value="Pause" id="timer_pause" />
<input type="button" value="Resume" id="timer_resume" />

的javascript:

var seconds_left = 60, interval;
function startTimer() {
    clearInterval(interval);
    interval = setInterval(function() {
        document.getElementById('timer_div').innerHTML = --seconds_left;

        if (seconds_left <= 0)
        {
            document.getElementById('timer_div').innerHTML = '...';
            clearInterval(interval);
        }
    }, 1000);
}
document.getElementById('timer_pause').onclick = function () {
    clearInterval(interval);
};
document.getElementById('timer_resume').onclick = function () {
    startTimer();
};
startTimer();

答案 3 :(得分:0)

http://jsfiddle.net/dpeDe/

TIME LEFT: <span id='timer_div'></span>
<button></button>

<script>
var seconds_left = 60;
var interval;
var playing = false;
var b = document.getElementsByTagName("button")[0];

function tick(){
    document.getElementById('timer_div').innerHTML = --seconds_left;
    if (seconds_left <= 0){
        document.getElementById('timer_div').innerHTML = '...';
        clearInterval(interval);
    }
}

function play(){
    interval = setInterval(tick, 1000);
    b.innerHTML = "&#x25a0; stop";
}

function pause(){
    clearInterval(interval);
    b.innerHTML = "&#x25ba; play";
}

b.onclick = function(){
    playing ? pause() : play();
    playing = !playing;
};

b.click();
</script>

P.S。不推荐使用<font>代码

答案 4 :(得分:0)

我编写了一个delta timing脚本(请参阅gist),可让您轻松启动和停止定时事件:

var span = document.querySelector("span");

var seconds = 60;

var timer = new DeltaTimer(function () {
    span.innerHTML = seconds ? seconds-- : (timer.stop(), "...");
}, 1000);

timer.start();

以上代码相当于您当前的代码。在其上添加一个停止按钮非常简单:

var running = true;

document.querySelector("button").addEventListener("click", function () {
    if (running) timer.stop();
    else timer.start();
    running =! running;
});

自己查看演示:http://jsfiddle.net/wa4ms/4/