I have been struggling to get my head around this for a while now.
I am attempting to create a countdown timer. Eventually I want it to reset after every 5 hours starting from 8am. But for now I can't figure out if im setting the hours, minutes and seconds correctly to count down together properly.
This is my code so far:
<?php
$timeTo = strtotime('08:00:00').'<br />';
$timeNow = strtotime('now').'<br />';
$differenceInSeconds = $timeTo - $timeNow;
?>
<script type="text/javascript">
var s= "<?php Print($differenceInSeconds);?>";
var h= Math.floor(s/3600);
s-= h*3600;
var m= Math.floor(s/60);
s -= m*60;
var counter=setInterval(timer, 1000); //1000 will run it every 1 second
function timer()
{
s=s-1;
if(h >= 0 && m >= 0 && s <= -1){
m=m-1;
s=59;
if(h>= 0 && m < 0 && s <= -1){
h=h-1;
m=59;
s=59;
if (s <= -1)
{
//counter ended, reset counter
return;
}
}
}
//Do code for showing the number of seconds here
document.getElementById("timer").innerHTML=(h <= 0 ? ' ' : h+"hr ")+(m <= 0 ? ' ' : m+"min ")+(s < 10 ? '0'+s : s+"secs "); // watch for spelling
}
</script>
Am I barking up the wrong tree here? I am new to times and javascript so finding it difficult.
I will not answer this. I will just try to lead you to the answer.
s <= -1
is logically equivalent to s < 0
. There is no confusion about it. Use the second one, it looks more clean.s=59;
and in the next line how on earth will if(h>= 0 && m < 0 &&
s <= -1 )
ever evaluate to true
?Similar other logical mistakes are present as well. Take some time and fix this. If you fix this on your own then you're one step closer to becoming a good programmer.
Happy Coding... :)