1

Take this number "#1" Make it turn to a "#2" in 5 seconds Then to a "#3" in 5 seconds

Is this possible, or how do i accomplish this?

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
Xavier D
  • 57
  • 1
  • 1
  • 8
  • Yes, you can do that in javascript quite easily. You should google for *javascript countdown timer*, there will be plenty of tutorials and you will learn some javascript code while doing it. Much better than just hoping someone will post a working script. – Fluffeh Jul 18 '12 at 05:00
  • yes its possible, tried anything? –  Jul 18 '12 at 05:00
  • This has been answered before on Stack Overflow: http://stackoverflow.com/questions/1191865/code-for-a-simple-javascript-countdown-timer – Dane Balia Jul 18 '12 at 05:06
  • try this http://jsfiddle.net/LXZy8/ – Kishore Jul 18 '12 at 05:14

1 Answers1

4

Because PHP executes on the server and only sends the resulting output to the browser, we can't use only PHP to update it.

Easiest method would be to use JavaScript's setTimeout method.

function update() {
  var counter = document.getElementById("counter");
  counter.innerText = counter.innerText*1 + 1;
  setTimeout(update, 1000);
} 

<body onload="update()">
  <div id="counter">0</div>
</body>

The update function gets called once on the body's load and then it calls itself after 1000ms to make a 1 second counter. Note: I have to multiply the innerText by 1 to convert a string to a number so it will add instead of concatenating.

Another way of doing this, although I don't know why you'd want to do it this way (but it uses PHP.. lol) is to refresh the page with an updated query string parameter.

<?PHP
$newcount = 0;
if(isset($_GET['count'])) {
    $newcount = $_GET['count'] + 1;
    echo $newcount;
}

echo "<meta http-equiv='refresh' content=\"1;URL='a.php?count={$newcount}'\">";
?>

Here I get the current value of the counter and add 1 using PHP and then echo a meta refresh tag to, after 1 second, refresh the page with the updated count value in the query string. Next time the page loads, it'll read that value, add one, refresh with the new value, etc. This is just to show you another way, I would not recommend doing this in your application!

sachleen
  • 30,730
  • 8
  • 78
  • 73
  • 1
    Anyone who uses the second version in a real-world scenario deserves to be beaten to death! Just because you CAN do something does NOT make it a good idea! – RonLugge Jul 18 '12 at 05:16
  • Ohh ok thank you lots. i got ` ` for ne one else who needs the quick code – Xavier D Jul 18 '12 at 05:24
  • 1
    @XavierD: Please don't actually pass strings to `setInterval`. it uses `eval`. Pass functions instead. `setInterval(timer, 1000);` or `setInterval(function(){ timer(); },1000);` – gen_Eric Jul 18 '12 at 05:31