我在PHP中遇到了sleep()函数的一些问题.
echo date('h:i:s') . "
";
//sleep for 5 seconds
if(1 == 1){
sleep(5);
//start again
echo date('h:i:s');
}
?>
当我运行此代码时,我会暂停5秒,然后将两个日期粘贴在一起,而不是一个日期,5秒暂停,然后是下一个日期.
有没有其他方法可以写这个,所以它正常工作?
解决方法:
// 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') . "
";
// 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();
您可以通过在每次调用flush()之前回显更多空格来提高稳健性.我之所以这么说,是因为服务器和用户浏览器之间可能存在多层软件,并且这些层中的任何一层都可能决定缓冲,直到它获得足够的数据来发送它感觉是合理大小的网络帧.用空格填充可能有助于破坏缓冲.
标签:php,sleep,delay
来源: https://codeday.me/bug/20190624/1279418.html