Skip to content Skip to sidebar Skip to footer

Javascript Count Down To Show Days?

I have this javascript countdown that will show seconds. I need to know how I can show days in the counter instead of second. i.e. 1 day, 2 hours left. this is the code:

Solution 1:

http://jsfiddle.net/h2DEr/1/

function updateCounter() {
    var msg = '';
    if (counter > 0) {
        counter -= 1;
        msg = convertSecondsToDays(counter); 
        setCookie('counter', counter, 1);
    }
    else {
        counter = MAX_COUNTER;
    }
    var el = document.getElementById('counter');
    if (el) {
        el.innerHTML = msg;
    }
}

Here is the function that converts seconds to days

function convertSecondsToDays(sec) {
  var days, hours,rem,mins,secs;
  days =  parseInt(sec/(24*3600));
  rem = sec - days*3600
  hours = parseInt(rem/3600);
  rem = rem - hours*3600;
  mins = parseInt(rem/60);
  secs = rem - mins*60;
  return days +" days " + hours +" hours "+mins + " mins "+ secs + " seconds";
}

update: after @sanya_zol's answer and comments from David Smith

since setInterval is not supposed to run every second, you need to change your strategy a little bit. I have modified the fiddle for that as well

  1. Set MAX_COUNTER to a value when you want it to expire.
  2. instead of decreasing the counter by -1, check the current time, subtract it from the expiry date and display it.

      EXPIRY_SECONDS = 24*60*60;
      MAX_COUNTER = parseInt(new Date().getTime()/(1000)) + EXPIRY_SECONDS;
    
      function updateCounter() {
         var msg = '',curTime = parseInt(new Date().getTime()/1000);
    
         if (curTime < MAX_COUNTER) {
            msg = convertSecondsToDays(MAX_COUNTER- curTime);
            setCookie('counter', MAX_COUNTER- curTime, 1);
         }
         else {
            MAX_COUNTER = parseInt(new Date().getTime()/1000) + EXPIRY_SECONDS;
         }
    
         var el = document.getElementById('counter');
         if (el) {
           el.innerHTML = msg
         }
       }
    

Solution 2:

counter_interval = window.setInterval(updateCounter, 1000); 

The 1000 is value in milliseconds so how many milliseconds are there in a day?

counter_interval = window.setInterval(updateCounter, 1000*60*60*24);

Solution 3:

addition to vdua's answer:

Your code is really badly written.

It uses setInterval which counter is not precise (moreover, it have very, very bad precision) - so your counter's second will be equal to 1.05-1.2 real seconds (difference between real time and counter will accumulate).

You should check system time (via (new Date).getTime() ) every time at lower intervals (like 100 ms) to get precise counter.


Post a Comment for "Javascript Count Down To Show Days?"