tags:

views:

44

answers:

3

I have the following:

echo time()."<br>";

sleep(1);
echo time()."<br>";

sleep(1);
echo time()."<br>";

I wrote the preceding code with intention to echo time()."<br>" ln 1,echo time()."<br>" ln 4, wait a final second and then echo the final time()."<br>". Altough the time bieng echoed is correct when it comes to the intervals between time(), all echo functions are echoeing after the total of the waiting period/parameters in each sleep function.

This is how the script runs:

  • Excutes.
  • Waits 2 secons.
  • echoes
    1275540664
    1275540665
    1275540666

Notice the correct incrementation in time() being echoed. My question is why is it not behaving like expected to where it echoes, waits a second, echoes again, waits one final second and then echos the last parameter?

I know my question is a little confusing due to my wording, but i will try my hardest to answer any comments regarding this, thanks.

+2  A: 

You have output buffering turned on.

It is more efficient for PHP to buffer up output and write it all to the browser in one go than it is to write the output in small bursts. So PHP will buffer the output and send it all in one go at the end (or once the buffer gets to a certain size).

You can manually flush the buffer by calling flush() after each call to echo (though I wouldn't recommend this is a "real" app - but then again, I wouldn't recommend calling sleep in a regular app, either!).

Dean Harding
Just a small side note: if this setting is turned on in your php.ini and you would like to disable this by default, change the output_buffering setting in your php.ini to 0 (http://www.php.net/manual/en/outcontrol.configuration.php)
phsource
@phsource: Good point. Though I would say that leaving it on and manually calling `flush` just for the times when you need it is probably better...
Dean Harding
Next side-note: Don't test a script like this on IE. It is known to render the site when it feels like it (e.g. tables are rendered when the closing table tag appears, not before). So even when using flush the IE won't render the output right away.
b_i_d
A: 

You can usually use ob_flush(), but it's definitely not reliable. And unfortunately, there's no other option.

Mikulas Dite
A: 

Why would output_buffering delay the execution of a function? Output buffering only buffers the output content and does not delay/buffer the execution of the code.

That being said, the above script should print the times with appropriate intervals. I bet it's something else.

Babiker: Did turning off ob fix your problem?

Farhad