David Bryce
David Bryce

Reputation: 23

How to create a countdown to a specific date in JavaScript

I'm having an incredibly difficult time figuring out how to get this JS code to count down to a specific date. I'm hoping to have this running live on a website to count down to October 20th (second from epoch: 1508457600, feel like thats important?). However, every time I refresh the website, the countdown starts from a preset time again.

The code I'm using is here:

<script>  
function getTimeRemaining(endtime) {
  var t = Date.parse(endtime) - Date.parse(new Date());
  var seconds = Math.floor((t / 1000) % 60);
  var minutes = Math.floor((t / 1000 / 60) % 60);
  var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
  var days = Math.floor(t / (1000 * 60 * 60 * 36));
  return {
    'total': t,
    'days': days,
    'hours': hours,
    'minutes': minutes,
    'seconds': seconds
  };
}

function initializeClock(id, endtime) {
  var clock = document.getElementById(id);
  var daysSpan = clock.querySelector('.days');
  var hoursSpan = clock.querySelector('.hours');
  var minutesSpan = clock.querySelector('.minutes');
  var secondsSpan = clock.querySelector('.seconds');

  function updateClock() {
    var t = getTimeRemaining(endtime);

    daysSpan.innerHTML = t.days;
    hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
    minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
    secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);

    if (t.total <= 0) {
      clearInterval(timeinterval);
    }
  }

  updateClock();
  var timeinterval = setInterval(updateClock, 1000);
}

var deadline = new Date(Date.parse(new Date()) + 15 * 24 * 60 * 60 * 1000);
initializeClock('clockdiv', deadline);
</script>

Would anybody be able to offer any insight into this?

Thanks in advance.

Upvotes: 1

Views: 3649

Answers (2)

xDreamCoding
xDreamCoding

Reputation: 1694

Try simplifying your code, you are doing a bunch of unnecessary stuff.

To get the Delta-Time try:

var delta = new Date(Date.now() - new Date(1508457600000));

then to get the seconds, minutes and so one use Date Methods:

var hoursSpan = delta.getHours();
var minutesSpan = delta.getMinutes();
var secondsSpan = delta.getSeconds();

for days see this

Upvotes: 1

Obsidian Age
Obsidian Age

Reputation: 42304

The problem isn't actually that your timer is 'resetting', but rather that you are counting down to a different time every time you refresh the page. This is because of your deadline, which takes a new Date(), and simply adds a bit of time to it:
var deadline = new Date(Date.parse(new Date()) + 15 * 24 * 60 * 60 * 1000).

In order to count down to a set time, you need to pass the target date inside the brackets of Date(), such as with var deadline = new Date("Jan 1, 2018 00:00:00").getTime().

You can use .getTime() to get the numeric value corresponding to the time for the specified date, according to UTC.

Hope this helps! :)

Upvotes: 1

Related Questions