Created
March 4, 2014 08:30
-
-
Save amirkheirabadi73/9342420 to your computer and use it in GitHub Desktop.
SetInterval In php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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>'; | |
} | |
setInterval('doit', 5000); // Invoke every five seconds, until user aborts script. | |
setInterval('doit', 1000, 100); // Invoke every second, up to 100 times. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
kind of cool