setInterval in PHP
JavaScript has a native method for executing a function periodically: setInterval. But in PHP, it’s a little bit harder. PHP lacks a setInterval equivalent. The closest we can get are the sleep(), usleep(), and time_nanosleep() functions. These functions delay script execution by a certain period of time (either seconds, microseconds, or a combination or seconds and nanoseconds).
PHP does, however, have a means of executing code as long as a condition is true: the while loop. What we can do, then is combine a while loop with one of the sleep functions — in this case usleep() — to create a setInterval equivalent. Check out the code below.
function setInterval($func = null, $interval = 0, $times = 0){
if( ($func == null) || (!function_exists($func)) ){
throw new Exception('We need a valid function.');
}
/*
usleep delays execution by the given number of microseconds.
JavaScript setInterval uses milliseconds. microsecond = one
millionth of a second. millisecond = 1/1000 of a second.
Multiplying $interval by 1000 to mimic JS.
*/
$seconds = $interval * 1000;
/*
If $times > 0, we will execute the number of times specified.
Otherwise, we will execute until the client aborts the script.
*/
if($times > 0){
$i = 0;
while($i < $times){
call_user_func($func);
$i++;
usleep( $seconds );
}
} else {
while(true){
call_user_func($func); // Call the function you've defined.
usleep( $seconds );
}
}
}
function doit(){
print 'done!<br>';
}
To invoke, do something similar to the following.
setInterval('doit', 5000); // Invoke every five seconds, until user aborts script.
setInterval('doit', 1000, 100); // Invoke every second, up to 100 times.
Here’s the catch: no data will be sent to the browser until the script has completely executed.