john
john

Reputation: 3

This loop won't echo my string

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>';
}

Upvotes: 0

Views: 158

Answers (4)

Skilldrick
Skilldrick

Reputation: 70869

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(); 
} 

Upvotes: 2

vava
vava

Reputation: 25381

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.

Upvotes: 1

Kamilos
Kamilos

Reputation: 805

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

Upvotes: 0

cjk
cjk

Reputation: 46465

It won't work until the server stops processing.

Upvotes: 2

Related Questions