倒数计时器加速

时间:2012-09-28 19:38:02

标签: javascript

我有一个计时器,每秒倒计时。计时器用于游戏:用户最多15秒 回答一个问题。假设游戏有10个问题。计时器适用于第一个问题 但随后,每个问题都会越来越快。任何建议都更受欢迎。谢谢!

代码在这里:

var timeInSecs;
var ticker;
function startTimer(secs) {
    timeInSecs = secs;
    ticker = setInterval("tick()", 1000); // every second
}
function tick() {
    var seconds = timeInSecs;
    if (seconds > 0) {
        timeInSecs--;
    }
    else if (seconds == 0) {
        document.getElementById("timeExpired").innerHTML = "Time expired!";
    }
    document.getElementById("countDown").innerHTML = seconds;
}
function myStopFunction() {
    clearInterval(ticker);
}​

4 个答案:

答案 0 :(得分:4)

else if(seconds==0)
        {
            // you should stop the timer here, and clear the interval
            myStopFunction();
            document.getElementById("timeExpired").innerHTML = "Time expired!";
        }

编辑:旁注

最好将函数tick传递给区间,而不是要评估的字符串。使用eval通常是一件危险的事情,而且效率较低。

setInterval(tick, 1000)

编辑:另一面注意事项

你可以更简洁地编写tick函数(并且没有额外的变量seconds

    function tick(){
        document.getElementById("countDown").innerHTML = timeInSecs;
        if(! timeInSecs--){
            myStopFunction()                
            document.getElementById("timeExpired").innerHTML = "Time expired!";
        }
    }

答案 1 :(得分:2)

我认为你应该在second函数中使用变量timeInSeconds而不是tick() - 。

因为您已将timeInSeconds的值赋予seconds。也许这会有所帮助。

答案 2 :(得分:1)

当你达到0时,我认为你没有清除间隔。

您定义了myStopFUnction(),但在秒== 0时可能永远不会调用它。

尝试:

else if (seconds == 0) {
    document.getElementById("timeExpired").innerHTML = "Time expired!";
    myStopFunction();
}

此外,您应该使用===

答案 3 :(得分:0)

var timeInSecs;
var ticker;
function startTimer(secs) 
{
    timeInSecs = secs;
}

function tick() {
    var seconds = timeInSecs;
    if (seconds > 0) 
      timeInSecs--;
    else if (seconds == 0) 
    {
        document.getElementById("timeExpired").innerHTML = "Time expired!";
    }
    document.getElementById("countDown").innerHTML = seconds;
    ticker = setInterval("tick()", 1000); // every second
}

function myStopFunction() 
{
    clearInterval(ticker);
} ​