Search code examples
javascripttimercountdown

Countdown can't be set to more than two days ahead


I have found a javascript code for a countdown timer in the internet and changed it a little bit to use it as I want.. It basically works fine, but as soon as I set the start date to more than 2 days ahead it doesn't to what it's supposed to. If I e.g. set it to three days ahead, as shown in the code below, it doesn't become a 72 hours countdown, but a 12 hours countdown.

I'm not sure whats the problem, because I can set up a 24 or a 48 hours countdown without any issues.

(function() {
 var start = new Date;
 start.setHours(18, 02, 20); 

function pad(num) {
  return ("0" + parseInt(num)).substr(-2);
}

 function tick() {
  var now = new Date;
var weekend = now.getDay();

if (now > start) { 
start.setDate(start.getDate() + 3);
  }

var remain = ((start - now) / 1000);
var hh = pad((remain / 60 / 60) % 60);
var mm = pad((remain / 60) % 60);
var ss = pad(remain % 60);
var distance = start - now;

document.getElementById('demo').innerHTML = hh + ":" + mm + ":" + ss

setTimeout(tick, 1000);
}
document.addEventListener('DOMContentLoaded', tick);
})();

Solution

  • The following line is the cause:

    var hh = pad((remain / 60 / 60) % 60);
    

    This caps the hours at 60 due to the % 60 (mod 60). 48 hours is less than 60 so it works. 72 hours will get translated to 12 (72 % 60 == 12).