Search code examples
javascripttimercountdown

Countdown Timer only counts down 1 second then stops


My countdown timer only counts down one second and then stops. I'm making a game that has a countdown clock and for ever incorrect answer, more time is added. I just can't get the timer to work.

var secondsLeft = document.getElementById("timer").textContent;

var timer = setInterval(function() {
    secondsLeft = 120;
    secondsLeft--;
    document.getElementById("timer").textContent = secondsLeft;
}, 1000);

I think I may need to do create a for loop, but everything I've read says I can do this without one. thanks!


Solution

  • Got it working! :D

    var secondsLeft = 120;
    var timer = setInterval(function() {
        secondsLeft--;
        document.getElementById("timer").textContent = secondsLeft;
    }, 1000);
    <span id="timer"></span>

    You were resetting the secondsLeft back to 120 by having it inside the timer function.