gp.
gp.

Reputation: 71

sleep and flush in php loop

I have the following code:

<?php
$initialSleep = ( isset($_GET['is']) ) ? $_GET['is'] : 0; // seconds - default 0 if not specified
$loopCount = ( isset($_GET['lc']) ) ? $_GET['lc'] : 1; // default 1 if not specified
$loopSleep = ( isset($_GET['ls']) ) ? $_GET['ls'] : 1; // seconds - default 0 if not specified

sleep($initialSleep);

for ( $i = 0; $i < $loopCount; $i++) {
    sleep($loopSleep);
    echo time();
    ob_flush();
}
?>

My problem is the instead of getting the time() echoed out at intervals I get a total delay equal to loopCount * loopSleep and then everything echoes out at once. I have seen other posts about this sort of thing and using flush() seems to fix it for most people - not me though.

Any help appreciated

Upvotes: 1

Views: 3048

Answers (2)

ontrack
ontrack

Reputation: 3043

Your webserver may buffer on it's own if it thinks it will get a more efficiënt transfer that way. Maybe you can turn this off but it's probably not the most efficient in production.

Upvotes: 0

xdazz
xdazz

Reputation: 160833

Try this:

ob_start();
for ( $i = 0; $i < $loopCount; $i++) {
    sleep($loopSleep);
    echo time();
    ob_flush();
    flush();
}

Upvotes: 2

Related Questions