Search code examples
javascripttimercountdowntimer

Auto Countdown Timer - Javascript



I'm trying to make my timer automatically change to a second new Date() after the first countdown is expired.
The purpose of this is in case I need to change date for the countdown, I won't have to manually edit and upload the js file after the it has expired. However I haven't managed to figure out how yet.

Below is the script that I've tried, output is "EXPIRED". Where did I do wrong? Thanks for your support!

<script>
// Set the date we're counting down to
var countDownDate = new Date("Jan 5, 2020 14:00:00").getTime();
var countDownDate2 = new Date("Jan 15, 2020 14:00:00").getTime();

// Update the count down every 1 second
var x = setInterval(function() {

  // Get today's date and time
  var now = new Date().getTime();

  // Find the distance between now and the count down date
  var distance = countDownDate - now;
  var distance2 = countDownDate2 - now;
  var a = distance;

  // Time calculations for days, hours, minutes and seconds
  var days = Math.floor(a / (1000 * 60 * 60 * 24));
  var hours = Math.floor((a % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((a % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((a % (1000 * 60)) / 1000);

  // Output the result in an element with id="demo"
  document.getElementById("demo").innerHTML = days + "d " + hours + "h "
  + minutes + "m " + seconds + "s ";

  // Change to another exp.
  if (distance < 0 && distance2 >0) {
   function changeDate() {
   a = distance2; 
   }
  }
  // If the count down is over, write some text 
  else {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "EXPIRED";
  }
}, 1000);
</script>

Solution

  • The first problem is that you look if distance is smaller than 1 and distance2 is bigger than one. But when distance is still active (which is the case at the time of writing) it will automatically go into the else branch.

    So to fix this you need:

    // If the count down is over, write some text 
    if (distance2 < 0) {
        clearInterval(x);
        document.getElementById("demo").innerHTML = "EXPIRED";
    }
    

    EDIT:

    The second problem is that you change the variable after it is being printed. So you have to go to the definition of a and change it from:

    var a = distance;
    

    To:

    var a;
    if (distance < 0 && distance2 >0) {
        a = distance2; 
    } else {
        a = distance;
    }