문제

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?

도움이 되었습니까?

해결책

// 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.

다른 팁

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');
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top