2

I can't get this code to do anything beyond counting down to 29 from 30. Does anyone have any insight or hints as to what I am doing wrong to cause it to only run once? I checked to make sure that all the functions are being called with console.logs on game.time (except the clearInterval one since it stops already after the first time through). How do I get the setInterval to keep looping until 0? Thanks in advance for any help! :)

//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);
Robert Prine
  • 2,633
  • 5
  • 14
  • 17
  • Hi Robert, welcome to SO! Thanks for a clear, well-formatted question with code examples :) – Ben May 01 '16 at 18:25

1 Answers1

2

setInterval takes a function refererence as a parameter, it should look like:

setInterval(game.count, 1000)

When you write it as game.count(), you're calling the count() method once, which is evaluated immediately.

Then, setInterval's signature will use the return value from that method instead of a function reference:

setInterval(whatever_the_return_value_was, 1000);

By passing only the reference (as game.count), the timer should work as expected. It will call the reference by itself, every 1000ms.

(MDN docs)

Ben
  • 54,723
  • 49
  • 178
  • 224