Javascript

Ajax Count Down Timer

This timer uses PHP and jQuery to show the server time. The server time will be the same for all users whereas a Javascript timer would be dependent on the local time on the device.

Here is the php code to generate the time:

<?php
 
// end time 2012-9-30 24:59:59 with server time compensated three hours
$target = mktime (23, 59, 59, 9, 30, 2012)-(3*60*60);
 
$difference=$target-time();
 
$days=floor($difference/60/60/24);
$days_remainder=$difference%(60*60*24);
 
$hours=floor($days_remainder/60/60);
$hours_remainder=$days_remainder%(60*60);
 
$minutes=floor($hours_remainder/60);
 
$seconds=$hours_remainder%60;
 
if($days == 1){
    echo "$days day $hours hours left";
}
 
else if($days > 1){
    echo "$days days left";
}
 
else if($hours > 1){
    echo "$hours hours $minutes min left";
}
else if($hours == 1){
    echo "$hours hour $minutes min left";
}
 
else if($minutes > 0){
    echo "$minutes min $seconds sec left";
}
 
else if($seconds > 0){
    echo "$seconds sec left";
}
 
else {
    echo "Auction Closed";
}
 
?>

The code below displays the time. It assumes jquery is loaded on the page.

<p id='days_left'></p>
<script type='text/javascript'>
$(document).ready(function(){
 
  /* auction timer */ 
  auctionTimer();
  setInterval(function(){auctionTimer()},1000);
  function auctionTimer(){
    console.log('check time');
    $('#days_left').load('auction_timer.php');
  }
 
}); </script>

Leave a Reply

Your email address will not be published. Required fields are marked *

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.