1

Below is my javascript code. It resets to 27 days 23 hours 59 minutes and 59 seconds whenever page reloads.

What changes I would do that it wont refresh after every time page reloads??

<script type="text/javascript">
    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 * 24));
        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()) + 28 * 24 * 60 * 60 * 1000);
    initializeClock('clockdiv', deadline);
</script>
Talha Awan
  • 4,573
  • 4
  • 25
  • 40
Anshul
  • 11
  • 2
  • 2
    you could save the current countdown value in some persistente storage mechanism (for example cookies or localStorage) – Cristian Lupascu Jul 27 '17 at 11:03
  • 2
    Your `deadline` always depends on the current Date at the moment the code is executed (`new Date()`). You should convert it to a specific Date. | Also, please, next time try searching before asking, I found a similar question by just searching your question's title. – yuriy636 Jul 27 '17 at 11:06

1 Answers1

2
var deadline = new Date(Date.parse(new Date()) + 28 * 24 * 60 * 60 * 1000);

You are creating a date from this exact moment, and then add 28 days. You should instead define your target date.

var deadline = new Date(year, month, day, hours, minutes, seconds, milliseconds);
//To find the remaining time until new Year you'd do
var deadline = new Date(2018, 0, 1);

The month is from 0 to 11, 11 being December. Read more about the date object https://www.w3schools.com/js/js_dates.asp

Salketer
  • 14,263
  • 2
  • 30
  • 58