我无法让这些代码做任何事情,除了从30减少到29之外。是否有人有任何见解或暗示我做错了导致它只运行一次?我检查确保在game.time上使用console.logs调用所有函数(除了clearInterval之外,因为它在第一次通过后已经停止)。如何让setInterval保持循环直到0?在此先感谢您的帮助! :)
//game object to contain variables and methods
var game = {
// variable for time
time: 30,
// Start button onclick creates the time remaining object and calls the forloop to start
start: function() {
// $("#time").html(game.time);
game.countdown = setInterval(game.count(), 1000);
}, //end of start function
//what the set interval does which is subtract one second from game.time
count: function() {
game.time--;
// if statement to check when time gets to zero
if (game.time <= 0) {
game.stop();
}
// puts the current time left on the page
else {
$("#time").html(game.time);
}
}, // End of count function
// stops the set interval
stop: function() {
clearInterval(game.countdown);
}, // end of stop function
}; // end game object
// Start button click calls the start method
$("#start").click(game.start);
答案 0 :(得分:2)
setInterval
将函数 refererence 作为参数,它应该如下所示:
setInterval(game.count, 1000)
当您将其写为game.count()
时,您只需调用count()
方法一次,即可立即评估。
然后,setInterval
的签名将使用该方法的返回值而不是函数引用:
setInterval(whatever_the_return_value_was, 1000);
通过仅传递引用(作为game.count
),计时器应按预期工作。它将每1000毫秒调用一次引用。
(MDN docs)