Frage

I am having some issues with the sleep() function in PHP.

<?php
echo date('h:i:s') . "<br>";

//sleep for 5 seconds
if(1 == 1){
sleep(5);

//start again
echo date('h:i:s');
}
?>

When I run this code, I get 5 seconds of pause, and then both dates pasted together, instead of one date, 5 seconds of pause, and then the next date.

Is there any alternate ways I could write this, so it works correctly?

War es hilfreich?

Lösung

// turn off all layers of output buffering, if any
while (ob_get_level()) {
    ob_end_flush();
}
// some browsers tend to buffer the first N bytes of output, refusing to render until then
// give them what they want...
echo str_repeat(' ', 1024);

echo date('h:i:s') . "<br>";
// force php to flush its output buffers. this also TRIES to tell the webserver to flush, but may not work.
flush();

sleep(5);

echo date('h:i:s');
flush();

you may improve robustness by echoing more spaces before each call to flush(). I say this because there's possibly many layers of software between the server and users browser, and any of those layers might decide to buffer until it gets enough data to send what it feels is a reasonably sized network frame. padding with spaces might help subvert the buffering.

Andere Tipps

You need Output buffer! Try tu use ob_start at the top, and after each sleep a flush

Example 1

ob_start();
echo date('h:i:s') . "<br>";

//sleep for 5 seconds
if(1 == 1){
    sleep(5);
    flush();
    ob_flush();

    //start again
    echo date('h:i:s');
}

Example 2

ob_implicit_flush(true);
echo date('h:i:s') . "<br>";

//sleep for 5 seconds
if(1 == 1){
    sleep(5);

    //start again
    echo date('h:i:s');
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top