[Solved] Countdown timer for hours, minutes, and seconds

The problem is if you save the time in cookie just before refresh and retrieve it after page loads it may not match the real current time because page may take arbitrary amount of time to refresh, 1st time it may be 1 sec 2nd time may be faster and take 0.5 sec due to factors like caching etc. for users on slower network it may be always more than 1-2 seconds. So the time on the page will always lag and won’t match the real current time after a few refreshes.

Looks like i was wrong browser don’t refresh the content already on the page until all required resources are downloaded so your counter keeps going as well as setting cookies until its all ready

Here is what i got to work

<div id="hms">02:00:00</div>

var startTime;
function getCookie(name) {
  var value = "; " + document.cookie;
  var parts = value.split("; " + name + "=");
  if (parts.length == 2) return parts.pop().split(";").shift();
} // credits kirlich @http://stackoverflow.com/questions/10730362/get-cookie-by-name

function count() {
 if(typeof getCookie('remaining')!= 'undefined')
   startTime = getCookie('remaining');
 else if(document.getElementById('hms').innerHTML.trim()!='')
   startTime = document.getElementById('hms').innerHTML;
  var d = new Date(); 
  var h=d.getHours(); 
  var m=d.getMinutes();
  var s=d.getSeconds();
  startTime = h+':'+m+':'+s;
  startTime  = d.toTimeString().split(" ")[0]

 var pieces = startTime.split(":");
 var time = new Date();
 var timediff = new Date(time.valueOf()-1000)
 var newtime = timediff.toTimeString().split(" ")[0];
 document.getElementById('hms').innerHTML=newtime ;
 document.cookie = "remaining="+newtime;


PS: Tried and tested the countdown survives page refresh and accurate even in heavy page throttling >10 seconds!

If you don’t want current time but any manual time entered you can always adjust the values to get the desired effect.


solved Countdown timer for hours, minutes, and seconds