Php:如何在延遲一秒后打印每個結果[重復]

[英]Php: how to print each result after a second of delay [duplicate]


This question already has an answer here:

這個問題在這里已有答案:

I want something like:

我想要的東西:

for($k=0;$k<20;$k++){
    echo $k;
}

Output:

0

Sleep for 1 second.

睡1秒鍾。

1

sleep for 1 second.

睡1秒鍾。

2

sleep for 1 second.

睡1秒鍾。

.

. .

5 个解决方案

#1


0  

If you're interested in having the variables appear on the page one by one, with a second delay in between, you'll need to use JavaScript rather than PHP. If you need input from PHP, use Ajax.

如果你有興趣讓變量逐一出現在頁面上,並且介於兩者之間,那么你需要使用JavaScript而不是PHP。如果需要PHP輸入,請使用Ajax。

PHP has an inbuilt function called sleep() (http://php.net/manual/en/function.sleep.php) that causes the code to delay for a given number of seconds. However, this will not have the behaviour you might expect, which is to say, echoing a variable, then waiting a second, then echoing another one. The script will simply take that many seconds longer to execute.

PHP有一個內置函數,名為sleep()(http://php.net/manual/en/function.sleep.php),它會導致代碼延遲給定的秒數。但是,這將沒有您可能期望的行為,也就是說,回顯變量,然后等待一秒,然后回顯另一個變量。該腳本將花費更長的時間來執行。

So, for example:

所以,例如:

for($k=0;$k<20;$k++){
    echo $k;
    sleep(1);
}

Will take 20 seconds to execute, but the page will still only load once.

執行需要20秒,但頁面仍然只會加載一次。

#2


0  

I think you're looking for output buffer:

我想你正在尋找輸出緩沖區:

for ($k = 0; $k < 20; $k++) {
    echo $k . '<br />';
    flush();
    ob_flush();
    sleep(1);
}

#3


-1  

use inbuilt sleep function //time in seconds

使用內置睡眠功能//以秒為單位的時間

for($k=0;$k<20;$k++){
    echo $k;
    sleep(1);
}

#4


-1  

From http://docs.php.net/Thread with pthreads

來自http://docs.php.net/Thread和pthreads

<?php

class workerThread extends Thread {
public function __construct($i){
  $this->i=$i;
}

public function run(){
  while(true){
   echo $this->i;
   sleep(1);
  }
}
}

for($i=0;$i<50;$i++){
$workers[$i]=new workerThread($i);
$workers[$i]->start();
}

#5


-1  

If you intend to do this at CLI, then you need to use sleep, like this

如果您打算在CLI中執行此操作,則需要使用sleep,就像這樣

for($k=0;$k<20;$k++){
    echo $k.'<br>Sleep for 1 second.';
    sleep(1);
}

However, if you intend to do this at the web-browser, then PHP runs at the server before the server responds to the client, therefore all your 20 seconds are spent on the server and the browser will receive all the output at once. Therefore, for browsers your approach is not adequate, instead of that, you might want to do a polling, or a setTimeout, or a setInterval. Since you are interested in PHP loops, I would like to suggest that you could run your PHP from command-line.

但是,如果您打算在Web瀏覽器上執行此操作,那么PHP會在服務器響應客戶端之前在服務器上運行,因此所有20秒都花在服務器上,瀏覽器將立即接收所有輸出。因此,對於瀏覽器,您的方法是不夠的,您可能希望進行輪詢,setTimeout或setInterval。由於您對PHP循環感興趣,我建議您可以從命令行運行PHP。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2016/12/23/36b63bbc13ea495d4eba6eb2e73df371.html



 
  © 2014-2022 ITdaan.com 联系我们: