David Alwis David Alwis - 4 months ago 19
Javascript Question

Javascript Countdown Timer Repeat and Count total that repeat

I have javascript countdown timer from 25 -> 0.

var count=25;

var counter=setInterval(timer, 1000); //1000 will run it every 1 second

function timer()
{
count=count-1;
if (count <= 0)
{
clearInterval(counter);
return;
}

document.getElementById("timer").innerHTML=count; // watch for spelling
}


div HTML

<span id="timer">25</span>


Now I want the countdown is repeat automatically after wait 5 seconds then it start again from 25 -> 0. And I want to count how many times that countdown repeat. Is it possible for that?

Please help.

Answer

You can try wrapping the entire code into a function (countTimers() in the example below) that runs every 30 seconds (5 seconds after each timer). Then, set a counter (timersCount in the example below) to count how many times that will run.

See the example below:

var timersCount = 0;
setInterval(countTimers, 30000);
countTimers();
function countTimers() {
    timersCount++;

    // as per request in the comments, you can set a timer counter as well:
    document.getElementById("totalcounter").innerHTML = timersCount;

    var count = 25;
    var counter = setInterval(timer, 1000);
    function timer() {
      count = count-1;
      document.getElementById("timer").innerHTML=count;
      if(count <= 0) {
        clearInterval(counter);
        return;
      }
    }

}
Timer: <span id="timer">25</span><br>
Number of times run: <span id="totalcounter">1</span>