2016-05-01 8 views
2

30から29までのカウントを超えてこのコードを実行することはできません。誰かが一度だけ実行するように間違っていることについての洞察やヒントはありますか?私は、すべての関数がgame.timeのconsole.logsで呼び出されていることを確認しました(clearIntervalを除く)。 setIntervalを0までループし続けるにはどうすればよいですか?助けをあらかじめありがとう!あなたはgame.count()としてそれを書くときに、あなたがある、一度count()メソッドを呼び出しているsetIntervalは継続しません

setInterval(game.count, 1000) 

::)

//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

こんにちはRobert、ようこそ!コード例を使用して明確で整形式の質問をいただきありがとうございます:) – Ben

答えて

2

setIntervalがパラメータとしてrefererenceを関数を受け取り、それは次のようになります。すぐに評価される。

そして、setIntervalの署名ではなく、関数参照のメソッドの戻り値を使用します。予想通り

setInterval(whatever_the_return_value_was, 1000); 

game.countなど)のみの参照を渡すことによって、タイマが動作しなければなりません。それはそれ自身で、毎1000msごとに参照を呼び出すでしょう。

MDN docs

+0

ありがとうございます。それはまさに何が間違っていた! –

関連する問題