我有一个每秒倒计时的计时器。计时器用于游戏:用户最多有 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);
}
最佳答案
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)
编辑:另一个旁注
您可以更加简洁地编写刻度函数(并且无需额外的变量秒
)
function tick(){
document.getElementById("countDown").innerHTML = timeInSecs;
if(! timeInSecs--){
myStopFunction()
document.getElementById("timeExpired").innerHTML = "Time expired!";
}
}
关于javascript - 倒数计时器加快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12646298/