PHP: sleep() for particular line of code

寵の児 提交于 2020-02-02 03:22:05

问题


is it possible to use sleep() (or some other function) to wait before execution?

I have for example:

<div>bla bla</div>
<?php
$a
echo $a; ?>

some divs and html
<?php
$b
echo $b; ?>

How to execute the first php script say 5 sec after the page has loaded but to show everything else as the page loads? If I use sleep() before the first php it will delay the whole page from loading.


回答1:


You want to use AJAX for this. Example using jQuery:

<div id="content">
<-- You want to load something here after 5 seconds -->
</div>

<script type="text/javascript">
    setTimeout(function() {
        $('#content').load("/url/to/your/script.php");
    }, 5000); // 5000 is the time to wait (ms) -> 5 seconds
</script>

This would load the output (echo) of script.php into the div with the ID "content". By doing it this way, you let the client do all the rendering work as already recommended by @GhostGambler

This will not block outputting other content sent by the initial script.




回答2:


Yes, you can use sleep() to delay execution, but since the output is usually buffered and isn't sent to the browser until the script has finished the result isn't what you're after.

If you do a flush() and ob_flush() right after calling sleep() the output buffer is flushed and sent to the browser.

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




回答3:


The HTTP protocol includes a special header, Transfer-Encoding, that allows you to specify that the page could be loaded in chunks (Transfer-Encoding: chunked), although there is no guarantee that the browser will do so (but most browsers will).

The Transfer-Encoding: chunked header signals to the browser that the web server does not know the Content-Length in advance.

While typically you want to use Ajax to load content after that page has been fully loaded, you can use this technique to show, for example, realtime terminal output, without needing JavaScript.

See this question on how to implement chunked responses in PHP.



来源:https://stackoverflow.com/questions/40018580/php-sleep-for-particular-line-of-code

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