如何恢复计时器?

时间:2015-06-10 01:33:49

标签: javascript timer resume

我试图实现一个从60秒开始倒计时的计时器。单击暂停按钮时,我可以暂停计时器,但是当我再次单击它以恢复时,它会将计时器重置为60秒。

以下是代码片段:

var t = 0;

function pause_game(pause_button){
    var elem = document.getElementById('pause_button');
    var lastTime;
    if (elem.value=="PAUSE"){
        lastTime = clearTimeout(t);
        elem.value = "RESUME";
    }
    if (elem.value=="RESUME"){
        countdownTimer(lastTime);
        elem.value = "PAUSE";
    }
}

function countdownTimer(secs) {
    var game_page = document.getElementById('game_page');
    var start_page = document.getElementById('start_page');
    var seconds = 60;
    function tick() {
        var counter = document.getElementById("timer");
        seconds--;
        counter.innerHTML = "0" + ":" + (seconds < 10 ? "0" : "") + String(seconds);
        if(seconds > 0) {
            t = setTimeout(tick, 1000);
        }
        else {
            setTimeout(function () {
            game_page.style.display = 'none';
            start_page.style.display = 'block';
            }, 1000)
        }
    tick();
}

似乎无法弄清楚出了什么问题。非常感谢帮助。谢谢!

2 个答案:

答案 0 :(得分:2)

t变量不会返回当前倒计时值,它会返回setTimeout id,用于取消超时功能。

所以你必须使用另一个变量来记录当前倒数秒和countDownTimer函数,而不是分配60到秒,分配记录的当前倒数秒。

或者您可以使用setInterval函数执行倒计时作业并设置暂停布尔值以表示状态:

var paused = false;
var t;
function countDownTimer(seconds){
    //before create another timer, remember to cancel the previous one, if has
    clearInterval(t);
    t = setInterval(function(){
        if(!paused){
          seconds--;
          console.log(seconds);
          //you can do display or whatever things here.
        }
    }, 1000)
}
function pauseOrResumeTimer(){
    paused = !paused;
}

答案 1 :(得分:1)

你不能恢复一个计时器 - 你可以做的就是捕捉你已经过了多少时间和剩下多少时间之间的差异&#34;暂停&#34;计时器,然后当你想要&#34;取消暂停&#34;你为那个剩余部分设置了一个新的计时器。

考虑一下我很久以前做过的骨干项目的片段:

/**
 * Method 'pauses' the timer by clearing the timer from the global
 * object timeout queue and logging the remaining time. When we 'unpause',
 * we simply create a new timer with the remaining time.
 * @return MEP.Timer
 */
pause : function () {
    // Don't try to pause if it is already paused.
    if (this.get('state') === 'live') {
        window.clearTimeout(this.get('timerId'));
        this.setRemainingTime(this.get('remaining') - (new Date() - this.get('start')));
        this.setState('paused');
    }
    return this;
},

/**
 * Method sets a timer with the remaining time from the previously paused
 * timer. New timers also call this method by adding the full timer delay
 * as the remaining delay to consolidate functionality.
 * @return MEP.Timer
 */
resume : function () {
    if (this.get('state') === 'paused') {
        this.createTimer(this.get('callback'), this.get('remaining'), null);
    }
    return this;
},