问题
I have foreach functions that print students names
$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?
回答1:
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.
回答2:
try using flush function
ob_start();
$names = array("Alex","Brad","Tom");
foreach($names as $name) {
echo "$name <br />";
ob_flush();
flush();
sleep(10);
}
回答3:
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.
回答4:
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
回答5:
You can write flush();
after echo
来源:https://stackoverflow.com/questions/6844889/how-can-i-run-php-script-with-timer