5

please tell me how to make a delay function to delay functions!

DelayCommand(functionToDelay, Delaytime);

..? in php 5.3+

thanks for any help

karim79
  • 339,989
  • 67
  • 413
  • 406
james
  • 413
  • 4
  • 7
  • 12

5 Answers5

3
function delayCommand($callback, $delayTime) {
    sleep($delayTime);
    $callback();
}
karim79
  • 339,989
  • 67
  • 413
  • 406
  • 3
    The problem with sleep though is that it affects the page on a global level even when it sits inside a function. This means you can't use this function in the middle of the page. Just to demonstrate my point, if you set the timer for 5 seconds and use the function in the middle of the page, the first half of the page would load but then the second half wouldn't load for 5 seconds. That draw back makes sleep seem like a pretty useless function to me. – Daniel Tonon Sep 25 '15 at 22:09
  • same issue i have @DanielTonon – Muhammad Ahmed Dec 30 '19 at 08:41
1

This should work, consider switching out sleep() to usleep().

function DelayCommand($functionToDelay, $delayTimeInSeconds) {
    sleep($delayTimeInSeconds);
    $functionToDelay();
}

DelayCommand(function() { echo "yes"; }, 5);

(Code is untested)

chelmertz
  • 20,399
  • 5
  • 40
  • 46
1
function delayCommay($function, $nano){
    usleep($nano);
    $function();
}

Will do the trick however it is synchronous. So if you make a call to delayCommand it will delay your whole script until it has run the command.

Paul
  • 139,544
  • 27
  • 275
  • 264
1

If you want it done asynchronously, see my answer here: Scheduling php scripts

For your information, here's a list of related functions:

  • sleep() / usleep() - Sleep for an amount of (micro)seconds.
  • time_sleep_until() - Sleep until a timestamp.
  • time_nanosleep() - Sleep for an amount of seconds and nanoseconds.
Community
  • 1
  • 1
Christian
  • 27,509
  • 17
  • 111
  • 155
0

Here is what I have for delaying a function in MS, Sleep and Usleep pause the execution of the whole script, this seems to work pretty well

    public function DelayTime($ms){ 
         $now = microtime();
         $finishtime = ($now + $ms);

         while($now < $finishtime){ 
             $now = time();
             if($now >= $finishtime){ break; }
         }
         return true;
     }