嗨,我正在制作一个涉及倒数计时器的游戏。我希望在单击计时器按钮时启动游戏,但此时我的计时器才会自行启动。我已经看过几个已经回答的不同问题但是它们对我没有用。有什么建议吗?
var seconds = 60;
function secondPassed() {
var minutes = Math.round((seconds - 30)/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Times Up!!!";
} else {
seconds--;
}
}
var countdownTimer = setInterval('secondPassed()', 1000);
答案 0 :(得分:2)
我猜你在点击按钮时调用countdownTimer
,如果是这样,你必须在函数中包装setInterval
。
var countdownTimer = setInterval('secondPassed()', 1000); //Without the wrapper it simply executes, when JS reaches this line
应该是
var countdownTimer = function(){setInterval('secondPassed()', 1000);}
答案 1 :(得分:1)
将setInterval添加到按钮的单击侦听器:
var btn = document.getElementById('BUTTON_ID');
btn.addEventListener('click', function() {
setInterval('secondPassed()', 1000);
});