简体   繁体   中英

How can i run php script with timer?

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?

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);
}

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

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:

In php CLI that code will work.

You can write flush(); after echo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM