Search code examples
javascripthtmlcountdown

Set date for countdown timer


I need to set countdown timer on my website. I have a deadline date and now the timer needs to countdown till that date.

My current code is:

  <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 * 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()) + 15 * 24 * 60 * 60 * 1000);
            initializeClock('clockdiv', deadline);
        </script>

With this code, every time I visit my website, the timer starts to countdown from "15days".


Solution

  • Sometimes it’s necessary to preserve the state of the clock for more than just the current page. For example, if we wanted a ten minute countdown across the site, we wouldn’t want the clock to reset every time the user goes to a different page or every time the user refreshes the page they are on.

    One solution is to save the clock’s end time in a cookie. That way, navigating to a new page won’t reset the end time to ten minutes from now.

    Here’s the logic:

    1. If a deadline was recorded in a cookie, use that deadline.
    2. If the cookie isn’t present, set a new deadline and store it in a cookie.

    To implement this, replace the deadline variable with the following:

    // if there's a cookie with the name myClock, use that value as the deadline
    if(document.cookie && document.cookie.match('myClock')){
      // get deadline value from cookie
      var deadline = document.cookie.match(/(^|;)myClock=([^;]+)/)[2];
    }
    
    // otherwise, set a deadline 10 minutes from now and 
    // save it in a cookie with that name
    else{
      // create deadline 10 minutes from now
      var timeInMinutes = 10;
      var currentTime = Date.parse(new Date());
      var deadline = new Date(currentTime + timeInMinutes*60*1000);
    
      // store deadline in cookie for future reference
      document.cookie = 'myClock=' + deadline + '; path=/; domain=.yourdomain.com';
    }
    

    EDITED:

    Also you can remove your code

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

    And replace with this line. You will create date for countdown

    var deadline = 'December 31 2018 23:59:59 GMT+0200';
    

    This is full code:

    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 = 'December 31 2018 23:59:59 GMT+0200';
    initializeClock('clockdiv', deadline);
    body{
    	text-align: center;
    	background: #fff;
      font-family: sans-serif;
      font-weight: 100;
    }
    
    #clockdiv{
    	font-family: sans-serif;
    	color: #fff;
    	display: inline-block;
    	font-weight: 100;
    	text-align: center;
    	font-size: 30px;
    }
    
    #clockdiv > div{
    	padding: 10px;
    	border-radius: 3px;
    	background: #a9a9a9;
    	display: inline-block;
    }
    
    #clockdiv div > span{
    	padding: 15px;
    	border-radius: 3px;
    	background: #585858;
    	display: inline-block;
    }
    
    .smalltext{
    	padding-top: 5px;
    	font-size: 16px;
    }  
    <div id="clockdiv">
      <div>
        <span class="days"></span>
        <div class="smalltext">Days</div>
      </div>
      <div>
        <span class="hours"></span>
        <div class="smalltext">Hours</div>
      </div>
      <div>
        <span class="minutes"></span>
        <div class="smalltext">Minutes</div>
      </div>
      <div>
        <span class="seconds"></span>
        <div class="smalltext">Seconds</div>
      </div>
    </div>