Tiffany B. Brown

a mish-mosh of stuff

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.

  • Gitlez

    What purpose could you possibly  have for a setInterval() Function? Anything you need to run multiple times, is either run on a loop, or better yet, as a CRON job.

    I have found your site’s articles on HTML5 to be enlightening and informative, but as a Developer, this article scares me :)

    Cheers,
    Gitlez

  • Anonymous

    My specific use case was for a server-sent events demo. I wanted to show one circumstance that could cause an error and how to handle it — in this case, the server stops sending data: http://people.opera.com/tiffanyb/2011/serversentevents/error/index.php. It’s probably not necessary for most server-side development needs. 

    I can, however, envision see a future scenario in which a developer might want to stream data from the server at regular intervals to a client of some kind, and that data is massaged on the server before being sent by the script. I don’t think it’s that crazy, though I admit it has a limited use case.

    I should hope that most PHP developers would know when to use a loop, when to use cron, and when a setInterval function might be useful. 

  • Gitlez

    In either case a simple for loop, with a sleep() or usleep() directive, as needed, would allow for the same functionality as well as better readability.

    The problem with New “Developers” is their over use of custom methods. Causing their scripts to be resource heavy and a bit of a drudge to read through. Plus they don’t understand how to code without they’re custom functions. Dangerous.

    Most PHP developers do not know when the appropriate  tool or method is better over another. I spend half my days tutorial new developers in the fact that they don’t have to re-invent pre-existing methods or processes. That the one draw back to PHP, is that everyone wants to be ‘cute’ with it. To be honest, that is a problem with most scriptors and programmers. They think the more ‘complex’ (read: spaghetti factory), their code is, the more advance they seem.

    As Albert Einstein said, if you can’t explain something simply, then you truly do not understand it.  Not that you do not understand it, as you clearly do…. As I catch myself mis-directing a lot of frustration towards you unwarranted or even unjustly.  I apologize for the rant, as it was not my intentions and I will take it somewhere more appropriate. Just please keep in mind, especially with PHP, that the majority of it’s “users” are self taught from online tutorials and examples, that all.

    Again, I apologize for the rant/flame, you are providing competent knowledge to the base. 

    Cheers,
    Gitlez

  • Anonymous

    Custom functions can provide greater readability and maintainability
    depending on the application. In a one-off script, the while loop would
    be all that’s needed. 

    I originally wrote the function to be flexible and reusable,
    and then realized that I didn’t need it after all. But since it was
    already written, why not share and hope someone gets something out of it?

    The above function actually does precisely what you suggest. It just
    wraps two different while loops in one function and uses one or the
    other depending on whether there’s a third parameter. Necessary? Again:
    depends on the specific use case.