Namatullah Namatullah - 6 months ago 25
Javascript Question

Countdown timer for hours, minutes, and seconds

How to set cookie for this count down timer?
The cookie should prevent resetting timer while I am refreshing the page.

<div id="hms">02:00:00</div>
<script type="text/javascript">
function count() {
var startTime = document.getElementById('hms').innerHTML;
var pieces = startTime.split(':');
var time = new Date();
time.setHours(pieces[0]);
time.setMinutes(pieces[1]);
time.setSeconds(pieces[2]);
var timedif = new Date(time.valueOf() - 1000);
var newtime = timedif.toTimeString().split(' ')[0];
document.getElementById('hms').innerHTML = newtime;
setTimeout(count,1000);
}
count();
</script>

Answer

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

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

<script>
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;
 }
 else
 {
  var d = new Date(); 
  var h=d.getHours(); 
  var m=d.getMinutes();
  var s=d.getSeconds();
  startTime = h+':'+m+':'+s;
  //OR
  startTime  = d.toTimeString().split(" ")[0]
 }

 var pieces = startTime.split(":");
 var time = new Date();
 time.setHours(pieces[0]);
 time.setMinutes(pieces[1]);
 time.setSeconds(pieces[2]);
 var timediff = new Date(time.valueOf()-1000)
 var newtime = timediff.toTimeString().split(" ")[0];
 document.getElementById('hms').innerHTML=newtime ;
 document.cookie = "remaining="+newtime;
 setTimeout(count,1000);
}
count();
</script>

</html>

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.