PHP output text before sleep

时间秒杀一切 提交于 2019-11-28 01:13:39

check this out

<?php

ob_start();

echo 'Output one.';
ob_flush();
usleep(1500000);
echo 'Output two.';
ob_flush();

?>

Pentium10's answer did not quite work for me.. However when I went to the PHP documentation page, there were a lot of good comments on there.

http://php.net/manual/en/function.ob-flush.php

This worked for me using Firefox 3.5.9, PHP 5.2.11, Apache running off local Windows 7 laptop:

echo "test";
ob_end_flush();
flush();
usleep(x);
echo "test";

The ob_end_flush() was crucial to getting data sent.

TooAngel

I think it is more a http request/response issue. On the command line your script works fine.

Normally the response is prepared completely and send to the client. If your response has such a size that multiple tcp packages have to be send, it could happen that the first packages are send, before you script is ready with processing. So it depends on the size of the output. Depending on the client/web browser, it could also happen that the first packages get rendered, before the complete response arrives at the client.

As Noufal Ibrahim answered while im typing, I totally agree with him. Do it in a asynchrone manner.

While Pentium10's solution will probably work, you might want to consider moving this to the client side. Have an async call to get the first value, print it, sleep for the required amount of time and then repeat for the second value.

Bô-ô Trương
echo 'Output one.';
ob_flush(); 
flush();
usleep(1500000);
echo 'Output two.';

Your problem is that this is PHP. It's a pre-processor. So the php script runs, outputs the first log, then sleeps, then outputs the second log, and only thén it's sent to and shown in your browser.

You need javascript if you want the delay to be visible on your browser screen.

function showLog () {
  $(".secondlog").show();
}

$(document).ready(function() {
  setTimeout(showLog,3000);
});
.firstlog {
  border: 1px solid #AEAEAE;
}

.secondlog {
  display: none;
  border: 1px solid #AEAEAE;
  margin-top: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="firstlog">
  Output of first log
</div>
<div class="secondlog">
  Output of second log
</div>

<p>Wait for 3 seconds...</p>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!