tags:

views:

67

answers:

4

I have an infinite loop that I want to sleep for a second but the browser just hangs and nothing echos. Can someone tell me why?

while(1)
{
    sleep(1);
    echo 'test'.'<br>';
}
+2  A: 

It won't work until the server stops processing.

ck
Thanks CK. Is there a way to achieve an infinite loop that will sleep for a few seconds or will I have to do something else? Any suggestions?
john
If you want it to end after a few seconds, is it really infinite?
GalacticCowboy
+2  A: 

You could try flushing the output buffer with flush(), but it's not guaranteed to work.

Try this function from PHP.net:

function flush_buffers() { 
    ob_end_flush(); 
    ob_flush(); 
    flush(); 
    ob_start(); 
}
Skilldrick
Hey Skilldrick, no.. I tried flush but it still hangs. Any suggestions?
john
I think you'll have to break the loop. Why does it need to be infinite? PHP scripts aren't meant to be long-running.
Skilldrick
If you want to continually update the page with more data, you might need to use JavaScript.
Skilldrick
+1  A: 

That's because PHP sends data to browser in big chunks. It is all about optimization, sending small data is bad for performance, you want it to be sent in huge enough blocks so overhead from transferring it (both in speed and actual traffic) would be relatively low. Couple of small strings is just not big enough. Try add a flush() right after the echo, it will force PHP send this string to the browser.

vava
Hi vava. Thanks. I tried that but flash doesn't seem to be a PHP function. :)
john
Did you mean flush?
john
obflush(). Thanks.
john
Just flush() should work too. You need ob_flush when you use all that ob_ family of output functions.
vava
A: 

Couse it's a infinite loop it never will send response or be break

Kamilos