Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading