0

I have a PHP script that calculates the difference between a set date and the current date (in h:m:s) and I'd like to use that data for a simple visual Javascript countdown timer (using the PHP variables). This is the PHP code:

$date = date('Y-m-d h:i:s a', time());
$d1 = new DateTime("2012-11-18 11:14:15");
$d2 = new DateTime($date);
$result = $d1->diff($d2);
$hours = ($result->d*24)+$result->h;
$minutes = $result->i;
$seconds = $result->s;

What would be your preferred and most efficient way to display a countdown timer in Javascript? (Using either $d1 and $d2 or $hours, $minutes, $seconds?)

Dxx
  • 934
  • 2
  • 11
  • 41
  • use [setTimeout](http://stackoverflow.com/questions/10312963/javascript-settimeout) on a one-second loop. – Blazemonger Nov 20 '12 at 14:44
  • Edited the post to explain I require a visualized countdown timer. I should've been more elaborate about what I meant. Apologies! – Dxx Nov 20 '12 at 14:46
  • It sounds like you want someone to write the complete JavaScript code for you. StackOverflow doesn't work that way. Please try something yourself, and then post a question here when you have a specific problem with that code. – Blazemonger Nov 20 '12 at 14:55
  • Dude, "That data" is on the server. JavaScript is on the client. Your design pattern makes no sense. – Diodeus - James MacFarlane Nov 20 '12 at 15:05
  • I have made several attempts to create it but the code simply wasn't working (my current Javascript knowledge is quite limited). I could post that code to have someone who wishes to help inspect it, tell me it's completely wrong and help me with a working solution, or I could save some people's time by not having to bother them to read my 'code of shame'. – Dxx Nov 20 '12 at 15:06
  • 1
    well it's not that rare to initialize javascript variables with PHP ones o.O. – Naryl Nov 20 '12 at 15:07
  • Diodeus, I thought using Javascript variables with PHP is a common occurence? At least I do it regularly. Either way your personal take on my design pattern isn't helping me find a solution to this problem :) – Dxx Nov 20 '12 at 15:11

2 Answers2

2

Maybe you could use some Jquery plugin, like this one: Jquery Countdown

If you don't want to use plugins the general idea is this:

  1. PHP writes the starting datetime to a HTML tag or to a javascrit variable.

    echo '<div id="year">$year</div>';

  2. In javascript you create a function that decreases a current datetime by 1 second, decreasing minutes, hours, etc, when necessary.

    function decrease_by_1_sec(){ ... }

  3. Next, on the $(document).ready() function you make the decrease_by_1_sec() function execute every second.

    setInterval(decrease_by_1_sec(), 1000);

And that's it! that's the general idea.

Naryl
  • 1,878
  • 1
  • 10
  • 12
0

Try this jQuery countdown plugin - http://keith-wood.name/countdown.html

Roman
  • 3,799
  • 4
  • 30
  • 41