Reputation: 1099
I've got sleep(n) in a loop that is intended to do output on a periodic cycle.
But when I run the loop, nothing happens until all of the seconds in the intended loop duration accrue collectively, after which all of the output comes spilling out at once.
Help. Thanks.
Upvotes: 2
Views: 458
Reputation: 1099
Argh, the site's not letting me add comment to mathroc's latest. So I'll put it here:
It didn't work for me. But the following is really weird: I accidentally stumbled upon some other sleep code on the web that I stuck in front of what I've got:
<HTML>
<BODY>
$c=0;
while($c <$chunks){
$rand = rand(2000000, 6000000);
echo '<br> . . . sleeping for ' . round(($rand / 1000000),2) . ' seconds . . . zzzzzzzzzzzzzz<br>';
flush();
usleep($rand);
$c++;
}
WHAT I'VE GOT BEGINS HERE:
<br />
<br />
This page is loading.<br />
<?php
for($i=0;$i<5;$i++){
flush(); sleep(2);
?>
Almost there...<br />
<?php
}
?>
<?php flush(); sleep(2); ?>
Done.<br />
</BODY>
</HTML>
...and now the lower block of code sleeps fine, sequentially. Output is properly staggered (instead of arriving all in a lump at the end of 10 secs).
It's weird because I don't know what the above is doing that would make everything in the block below work all right. If I remove it, my block doesn't work (i.e., the output accumulates and then spills en masse at the end). If I remove only bits and pieces of the code above, then my thing wants to jump forward a little (but sequentially outputs the rest fine).
I have no idea what the preceding code is doing that makes my (latter block) work the way it should, or how to abbreviate it so that it still makes the latter block fully work, or even how to make the above code invisible on the page while still allowing the latter block to work accurately.
(I've tested the script on both Windows 7 Caucho Resin PHP 5 and Linux Apache CGI-BIN PHP 4 platforms. Identical results.)
Upvotes: 1
Reputation: 5695
try that:
ob_end_flush (); // just in case
while (1) {
echo 'wait for it<br/>'.PHP_EOL;
flush ();
sleep (2);
}
Upvotes: 7
Reputation: 1459
It sounds like you should be using flush() instead of sleep().
https://www.php.net/manual/en/function.flush.php
Upvotes: -1
Reputation: 16249
Maybe you need to flush() the output buffer after each piece of output?
Upvotes: 4