The Web Design Group

... Making the Web accessible to all.

Welcome Guest ( Log In | Register )

> Making countdown after adding days to today JS
hid
post Feb 13 2020, 09:59 AM
Post #1





Group: Members
Posts: 2
Joined: 13-February 20
Member No.: 27,166



I am making a countdown like this:

CODE

  Date.prototype.addDays = function(d){
    return new Date(this.valueOf()+864E5*d);
  };

  // get cd date
  var cdDate = new Date().addDays(5);

  var cd = setInterval(function(){
    // Get time now
    var now = Date.now();

    // Get distance between now and cdDate
    var distance = cdDate - now;

    // Get time left
    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);

    // Update UI
    ui_days.firstElementChild.textContent = days;
    ui_hours.firstElementChild.textContent = hours;
    ui_minutes.firstElementChild.textContent = minutes;
    ui_second.firstElementChild.textContent = seconds;
  }, 1000);


I'm confused on why whenever the page is loaded/refreshed the counter starts at 5 days when it should be somewhere around 4 days and ~10 hours.

I believe it has something to do with when I declare the variable cdDate, because when I make it statically without using .addDays it seems to work:

CODE
  var cdDate = new Date(2020, 6, 5, 5, 55, 25, 552);


How can I fix this so I can use .addDays and have the timer work properly?
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post

Posts in this topic


Reply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 



- Lo-Fi Version Time is now: 23rd April 2024 - 04:08 PM