setInterval 不继续

setInterval not continuing

除了从 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);

setInterval 接受一个函数 refererence 作为参数,它应该是这样的:

setInterval(game.count, 1000)

当您将其写为 game.count() 时,您将调用一次 count() 方法,该方法会立即被评估。

然后,setInterval 的签名将使用该方法中的 return 值而不是函数引用:

setInterval(whatever_the_return_value_was, 1000);

通过仅传递引用(如 game.count),计时器应该按预期工作。它会自己调用引用,每 1000 毫秒。

(MDN docs)