'Create Time Countdown in Javascript

Iam creating a workout countdown timer using javascript.

This is my code

var counter = 30;

setInterval( function(){
  counter--;

  if( counter >= 0 ){
    id = document.getElementById("count");
    id.innerHTML = counter;
  }

  if( counter === 0 ){
    id.innerHTML = "REST";
  }
}, 1000);
<div class="container">
      <h1 id="count">WORK</h1>
</div>
    

The time countdown running well, but i want to add a rest time countdown after 30sec workout.

Please Help me Thanks...



Solution 1:[1]

You should put the id outside of current scope, and also clear interval:

var counter = 30;

var intervalId = setInterval( function(){
  counter--;
  var id = document.getElementById("count");

  if( counter >= 0 ){
    id.innerHTML = counter;
  }

  if( counter === 0 ){
    id.innerHTML = "REST";
    clearInterval(intervalId)
  }
}, 1000);

Solution 2:[2]

You can have a function which accepts trainingTime aswell as restTime and display one of them conditionally on every interval.

function startTraining(trainingTime, restTime) {

    const fullTime = trainingTime + restTime
    var counter = 0

    const display = (value) => {
        id = document.getElementById("count");
        id.innerHTML = value;
    }

    // display the start time immediatly!.
    display('TRAIN: ' + fullTime)

    const interval = setInterval(function () {
        counter++;


        // stop training if fulltime is reached/exceeded
        if (counter >= fullTime) {
            clearInterval(interval)
            display('training ended')
            // start next training here!.  
            // ...        
        }

        else {
            // calculate remaining time
            const remainingTime = fullTime - counter

            // Display "TRAIN" if counter is less than needed trainingTime 
            // else display "REST"
            const keyword = counter < trainingTime ? 'TRAIN' : 'REST'

            // update html:
            display(keyword + ': ' + remainingTime)
        }

}, 1000);
}

const trainingTime = 15
const restTime = 15
startTraining(trainingTime, restTime)
<div class="container">
      <h1 id="count">WORK</h1>
</div>

With above snippet you can also know the exact moment a training ended.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Huan Le
Solution 2