1

Here is my code:

<?php
for($j = 0; $j < 10; $j++){
    print((string)$j . " ");
    sleep(1);
}
?>

The code waits to print

0 1 2 3 4 5 6 7 8 9

until after 10 seconds have elapsed, instead of printing one each second.

Why is this, and how can I fix it?

Ryan
  • 105
  • 4
  • 14
  • `sleep(1)` will wait for 1 second, which is ran 10 times so it waits 10 seconds. The results from the server are only given to the browser once after everything ran. – Spencer Wieczorek May 31 '17 at 15:57
  • Server side vs client side code execution. Use JavaScript for the client side. – Steve May 31 '17 at 15:58
  • Possible duplicate of [PHP: sleep() for particular line of code](https://stackoverflow.com/questions/40018580/php-sleep-for-particular-line-of-code) – Don't Panic May 31 '17 at 16:02
  • Also: https://stackoverflow.com/questions/3685760/php-output-data-before-and-after-sleep – Don't Panic May 31 '17 at 16:02

1 Answers1

1

Servers usually buffer the output of a server side script until there's enough in it to output try something like this. Combination of setting output buffering off and manually flushing the buffer. Note the implcit flush line and the flush and ob_flush lines.

<?php 
@ini_set("output_buffering", "Off");
@ini_set('implicit_flush', 1);
@ini_set('zlib.output_compression', 0);
@ini_set('max_execution_time',1200);


header( 'Content-type: text/html; charset=utf-8' );


echo "Testing time out in seconds\n";
for ($i = 0; $i < 10; $i++) {
    echo $i." -- ";

    if(sleep(1)!=0)
    {
        echo "sleep failed script terminating"; 
        break;
    }
    flush();
    ob_flush();
}

?>
Adharsh M
  • 2,773
  • 2
  • 20
  • 33