Skip to content

Instantly share code, notes, and snippets.

@amirkheirabadi73
Created March 4, 2014 08:30
Show Gist options
  • Select an option

  • Save amirkheirabadi73/9342420 to your computer and use it in GitHub Desktop.

Select an option

Save amirkheirabadi73/9342420 to your computer and use it in GitHub Desktop.
SetInterval In php
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.
@dishant-dave
Copy link
Copy Markdown

Is there any body who can give me preview. Because this is not working for me. Or may be i am wrong. Please guide me.

@CommandString
Copy link
Copy Markdown

Is there any body who can give me preview. Because this is not working for me. Or may be i am wrong. Please guide me.

If your website is crashing this is because PHP isn't an asynchronous script like JS. Which means during the time the script is running usleep(); the whole page is frozen. While JS can use setInterval(); and still run other functions in the background, your best bet is to use AJAX and call you PHP function from JavaScript. A couple Google searches should help.

@StadiaPS
Copy link
Copy Markdown

StadiaPS commented Aug 7, 2021

kind of cool

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment