Timed loop in php

10.9k views Asked by At

I just want to print a counting from 1 to 10 at an interval of 10 sec between each integer.

eg.

$i=10; //Time delay    
for($j=1;$j<11;$j++)  
{  
    echo $j;  
    //do something to delay the execution by $i seconds  
}

I have tried everything including flush(), ob_flush(), ob_implicit_flush() but all i get is a frozen screen untill the whole time is executed.

5

There are 5 answers

0
OptimusCrime On

What you want is much more javascript-related than PHP. Because PHP is serverside it is not designed to do these kind of operations. You COULD get it to work, but it would not be very pretty.

In my logic; counting from 1 to 10 should not involve the server at all. You can do this directly in the browser, hence use javascript.

2
Tim On

http://php.net/manual/en/function.sleep.php

The sleep function will interrupt execution of your script.

But have you considered using Javascript for something like this? Your script may reach maximum execution time, and will be hogging resources on the server. Use the client's resources instead!

0
Roman Newaza On

Yes, use Javascript as it's not possible to accomplish this task with PHP using HTTP because of output buffering.

1
AudioBubble On

you want to print the countdown while your php script is running? if yes, then try that non-recommended fragment:

ob_start();
for($i=0;$i<10;$i++) {
   echo str_repeat(" ",10000);
   echo 'printing...<br />';
   ob_flush();
   flush();
   sleep(1);
}

you see, the strange line:

echo str_repeat(" ",10000);

it seems that browsers needs some "data" before deciding to really flush your data. Use javascript for real time counters.

0
Andrius Naruševičius On

Use jQuery. On $(document).ready add a delay of 10 seconds to show a specific div which would contain the info to appear after 10 seconds.

For ready - http://api.jquery.com/ready/

For delay - http://api.jquery.com/delay/