Search code examples
javascriptfunctiontimercountercountdown

setting a one minute timer in JavaScript memory aid game


<div id="counter">1:00</div>
function countdown() {
var secs = 60;
function tick() {
    var counter = document.getElementById("counter");
    secs--;
    counter.innerHTML = "0:" + (secs < 10 ? "0" : "") + String(secs);
    if( secs > 0 ) {
        setTimeout(tick, 1000);
    } else {
        alert("Game Over");
    }
}
tick();
}

countdown(60);

I am having a problem with this portion of my game. I'm trying to set a 60 seconds timer for the game that starts at 60 and ends at 0, when it gets to 0 the game stops and an alert shows that the game is over.

I am very new to programming, so please give me as many feedbacks as you can. I found this code on the internet, and I figured out most of it, could you also tell me what does the tick() function do over here?


Solution

  • Here is one way you can do it:

    First declare a variable you will use for an interval (should be 'global', attached to window):

    var countDownInterval = null;
    

    Then, a function to trigger the tick interval, you should call this whenever the game is ready to start:

    function startCountDown()
    {
        countDownInterval = setInterval(tick,1000); //sets an interval with a pointer to the tick function, called every 1000ms
    }
    

    which will call the tick function every second:

    function tick()
    {
        // Check to see if the counter has been initialized
        if ( typeof countDownInterval.counter == 'undefined' )
        {
            // It has not... perform the initialization
            countDownInterval.counter = 0; //or 60 and countdown to 0
        }
        else
        {
            countDownInterval.counter++; //or --
        }
    
    
        console.log(countDownInterval.counter); //You can always check out your count @ the log console.
    
        //Update your html/css/images/anything you need to do, e.g. show the count.
    
        if(60<= countDownInterval.counter) //if limit has been reached
        {
            stopGame(); //function which will clear the interval and do whatever else you need to do.
        }
    
    }
    

    and then the function where you can do everything you need to do after game has finished:

    function stopGame()
    {
        clearInterval(countDownInterval);//Stops the interval
        //Then do anything else you want to do, call game over functions, etc.
    }
    

    You can fire up the counter at any time by calling startCountDown();