Josh G.
Josh G.

Reputation: 27

Stop countdown timer at 0

I have a countdown timer that is working, but I cannot figure out how to get it to stop at 0.

Here's what I have:

let totalTime = 10;
let timeElapsed = 0;
let interval;
let currentQuestion = 0;
let currentAnswer = 0;


function startTimer() {
    runTimer.textContent = totalTime;
    interval = setInterval(function () {
        totalTime--;
        runTimer.textContent = totalTime;
        }
, 1000);
    if (interval <= 0) {
        stopTimer(); 
    }
}


function stopTimer() {
    clearInterval(interval);
}

I tried creating an if statement to clearInterval once the timer reaches 0 but something is not right.

Upvotes: 0

Views: 562

Answers (1)

Ian
Ian

Reputation: 36

Just check if totalTime is <= 0 but inside the setInterval function like this.

function startTimer() {
    runTimer.textContent = totalTime;
    interval = setInterval(function () {
        totalTime--;
        runTimer.textContent = totalTime;
        if (totalTime <= 0) {
          stopTimer();
        }
     } , 1000);
}

Upvotes: 2

Related Questions