Search code examples
javascriptloopstimersettimeoutcountdown

How to put this timer in a loop? JS


  function countdown() {
        var secs = 60;
        function timer() {
            var counter = document.getElementById("counter");
            secs--;
            counter.innerHTML = "0:" + (secs< 10 ? "0" : "") + String(secs);
            if( secs > 0 ) {
                setTimeout(timer, 1000);
            } else {
                alert("Game over, you did not get to finish the game on time :( ");
                document.getElementById('memory_board').innerHTML = "";
                        newBoard();
            }
        }
        timer();
    }

    countdown();

How can I place this code in a loop? It's basically a timer which starts at 60 and ends at 0, and when that happens, the game restarts. I have no problem with the game restarting, but I just don't know how to put this code on a loop. I have looked in codeacademy and it says for a loop I have to use

for (var x; y;z ) {
    //code
}

where x is the start y is where it ends and z is how does it change. Please help me work this out, I'm a little confused.


Solution

  • You might want to look into using setInterval. It calls a given function every n millaseconds. You could structure your countdown function like so:

    function countdown(seconds) {
        var interval = setInterval(function() {
            if (seconds < 0) clearInterval(interval); //break the interval
            seconds--;
            //code
        }, 1000); //time in millaseconds to wait
    }