Search code examples
javascripthtmltimercountdowntimer

Multiple countdown timer


This js countdown timer is working fine but on multiple timers it is only working on the last div. How will it run on all the divs ? It should work on all the divs as there will be more than two timers. Any guidance will be really appreciated.

This is my code:

Fiddle

HTML & JS.

    <div id="timez1"></div>
    <div id="timez2"></div>

      var m = 1;
  function countdowny(){
  if(daysy == 0 && hoursy == 0 && minutesy == 0 && secondsy == 0){
    //seconds = 0;
    timez.innerHTML = "Auction Ended";
    }
    else{
      if(secondsy == 0){
          secondsy = 59;
          minutesy--;
        }else{
        secondsy--;
        }
        if(minutesy == -1){
        minutesy = 59;
          hoursy--;
         }
         if(hoursy == -1){
           hoursy = 23;
           daysy--;
      }
      if(daysy == -1){
           daysy = 0;
      }

      timez.innerHTML = "<span class=''>"+daysy+"D</span><span class=''> "+hoursy+"H</span><span class=''> "+minutesy+"M</span><span class=''> "+secondsy+"S</span>";
      setTimeout(countdowny,1000);   
      }
  }

  var daysy=3;hoursy=3;minutesy=3;secondsy=3;
    var timez = document.getElementById("timez"+m);
    countdowny();
    m++;

      var daysy=2;hoursy=2;minutesy=2;secondsy=2;
    var timez = document.getElementById("timez"+m);
    countdowny();
    m++;

Solution

  • First of all I think the whole design is broken. You should consider to reuse an existing countdown widget. (The simplest possible JavaScript countdown timer?)

    In your specific case,the issue is your setTimeout. It will run your countdowny method again and again, but always with the global varibales.

    So you'd need to refactor and give the element you want to update (and the remaining time) into the countdown function.

    function countdowny(element, remainingTime) {
       if(remainingTime.daysy == 0 && remainingTime.hoursy == 0 && remainingTime.minutesy == 0 && remainingTime.secondsy == 0){
          //seconds = 0;
          element.innerHTML = "Auction Ended";
       }
       else{
          //Calc date as before
          element.innerHTML = "<span class=''>"+remainingTime.daysy+"D</span><span class=''> "+remainingTime.hoursy+"H</span><span class=''> "+remainingTime.minutesy+"M</span><span class=''> "+remainingTime.secondsy+"S</span>";
          setTimeout(countdowny,1000, element, remainingTime);   
      }
    }
    
    var remainingTime = { daysy:3, hoursy: 3, minutesy:3, secondsy:3 };
    var timez = document.getElementById("timez"+m);
    countdowny(timez, remainingTime);