开发者

How can i run php script with timer?

I have foreach functions that print students names

$开发者_JS百科names = array("Alex","Brad","Tom");
foreach($names as $name) {
   echo "$name <br />";
   sleep(3);
}

How can i print each name, each 3 seconds? After "echo $name" i need some timer to stop the loop and wait for 3 seconds. sleep() functions doesn't work here. What else i can do?


You can not do this server side (reliably). This is because there is just too much possibility of your traffic being held or buffered on the way: by the webserver, by proxies along the way, by your browser, etc. It would however probably work on CLI.

So I would definitely do it client-side, without sacrificing security (if needed).

If this is only for "cosmetic" purposes, you can create an AJAX method which will return the array of names, and then have Javascript output them with its timers.

Or, you could have AJAX call the PHP script using timers, and PHP will return only one name. It can save the current timestamp in the DB or in a Session variable, and don't return a new name until some time has passed.


try using flush function

ob_start();    
$names = array("Alex","Brad","Tom");
foreach($names as $name) {
   echo "$name <br />";
   ob_flush();
   flush();    
   sleep(10);
}


If you need to do this in a web page you need to flush the output or disable output buffering to get that work. Some references:

  • http://php.net/manual/en/book.outcontrol.php
  • http://php.net/manual/en/function.flush.php

In php CLI that code will work.


You can do this with javascript, ajax

or with flush() function

<?php
$names = array("Alex","Brad","Tom");
foreach($names as $name) {
   echo "$name <br />";
   flush();
   sleep(3);
}

working demo


You can write flush(); after echo

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜