I have tried to create countdown timer from database. I have sent deltaTimeServer to JS. The output are right but they are freezing (not counting down, I have to press F5). Any idea for me?
Here is my code.
JS
<script type="text/javascript">
function countDown(){
$(".show").each(function() {
var elm = $(this);
var difTime=this.timestamp;
var day=0,hours=0,minutes=0,seconds=0;
if(difTime>0){
day=Math.floor(difTime/84600);
hours=(Math.floor((difTime/3600))%24) + day*24 ;
minutes=Math.floor(difTime/60)%60;
seconds=Math.floor(difTime)%60;
}
else{
elm.removeClass("show"); //for remove class show
}
elm.html(hours+' H '+minutes+' M '+seconds+' S ');
});
}
function countDown_onLoad(){
$(".show").each(function() {
this.timestamp = parseInt(this.firstChild.nodeValue,10);
});
setInterval(countDown,1000);
}
$(document).ready(function() {
countDown_onLoad();
});
</script>
PHP
$show=mysql_query("SELECT * FROM `room_lists` WHERE `active` = 1");
while ($array = mysql_fetch_array($show))
{
$timeStop = $array['timeStop'];
$deltaTimeServer = strtotime($timeStop)-strtotime(date('Y-m-d H:i:s'));
echo "<td align = 'center'><div class=\"show\">".$deltaTimeServer."</div></td>";
}
The problem in you JS is that your difTime is always the same. You have to subtract the current timestamp from the original
this.timestamp.But, it’s even easier since you’re counting down every second. You can just decrement the timestamp:
And that should do it.
Also, you can change this:
To this:
Finally, I would hide the
tdwithstyle="display:none"when you output it in PHP. Once the timestamp is set you can clear out thetdand show it – this way people don’t see a time stamp that turns into a counter.