Search code examples
javascriptcountdowntimer

Get custom attribute value for countdown timer (timer shows NaN)


Can't assign the end date to the variable for the timer to work. As a result, I get NaN Can you please tell me what is the mistake?

var countDownDate = new Date($("countdown").data("datetime")).getTime();

function ctd() {
  var now = new Date().getTime();
  var distance = countDownDate - now;
  var days = Math.floor(distance / (1000 * 60 * 60 * 24));
  var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);
  countdown = document.getElementsByClassName("countdown");
  countdown[0].innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
  if (distance < 0) {
    clearInterval(x);
    countdown.innerHTML = "Item expired!";
  }
}
ctd();
var x = setInterval(ctd, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<time class="countdown" datetime="2020-11-22T16:20:22+00:00"></time>


Solution

  • You repeat some of the time calculations every second, better use some const instead:

    const eCountDown = document.querySelector('.countdown')
      ,   one_Sec    = 1000
      ,   one_Min    = one_Sec * 60
      ,   one_Hour   = one_Min * 60 
      ,   one_Day    = one_Hour * 24
      ;
    var countDownDate = new Date(eCountDown.dateTime).getTime()
      ;
    function ctd()
      {
      let now      = new Date().getTime()
        , distance = countDownDate - now
        , days     = Math.floor(distance / one_Day)
        , hours    = Math.floor((distance % one_Day)  / one_Hour)
        , minutes  = Math.floor((distance % one_Hour) / one_Min)
        , seconds  = Math.floor((distance % one_Min)  / one_Sec)
        ;
      eCountDown.textContent = days + 'd ' 
                             + hours + 'h ' 
                             + minutes + 'm ' 
                             + seconds + 's '
                             ;
      if (distance < 0)
        {
        clearInterval(timerIntv)
        countdown.textContent = 'Item expired!'
        }
      }
    ctd()
    var timerIntv = setInterval(ctd, 1000)
    <time class="countdown" datetime="2020-11-22T16:20:22+00:00"></time>