Is there a set timeout in php?

Is there any PHP equivalent for setting timeouts in JavaScript?

In JavaScript, you can execute code after a certain time using the set timeout function.

Is it possible to do this in PHP?

+7
source share
5 answers

You can use the sleep() function:

 int sleep ( int $seconds ) // Delays the program execution for the given number of seconds. 

Example:

 public function sleep(){ sleep(1); return 'slept for 1 second'; } 
+1
source

PHP is single-threaded, and in general, PHP is focused on the HTTP request loop, so it would not be easy to let the timeout run the code, possibly after the request is complete.

I can suggest you learn Gearman as a solution to delegate work to other PHP processes.

+3
source

This is ugly, but basically works:

 <?php declare(ticks=1); function setInterval($callback, $ms, $max = 0) { $last = microtime(true); $seconds = $ms / 1000; register_tick_function(function() use (&$last, $callback, $seconds, $max) { static $busy = false; static $n = 0; if ($busy) return; $busy = true; $now = microtime(true); while ($now - $last > $seconds) { if ($max && $n == $max) break; ++$n; $last += $seconds; $callback(); } $busy = false; }); } function setTimeout($callback, $ms) { setInterval($callback, $ms, 1); } // user code: setInterval(function() { echo microtime(true), "\n"; }, 100); // every 10th of a second while (true) usleep(1); 

The interval callback function is called only after a ticking PHP statement. Therefore, if you try to call a function 10 times per second, but you call sleep(10) , you will get 100 executions of your tick function in the packet after the sleep is completed.

Note that there is an additional parameter, setInterval , which limits the number of times it is called. setTimeout simply calls setInterval with a limit of one.

It would be better if unregister_tick_function was called after it expired, but I'm not sure that it would be possible even if there wasn’t a main tick function that controlled and did not register them.

I have not tried to implement anything like this because it is not how PHP is intended to be used. There is probably a much better way to do what you want to do.

+2
source

Without knowing the use case for your question, it is difficult to answer it:

  • If you want to send additional data to the client a bit later, you can execute JS timeout on the client side with a handler that will make a new HTTP request for PHP.
  • If you want to schedule a task later, you can save it in the database and query the database at regular intervals. This is not the best solution, but relatively easy to implement.
0
source
-one
source

All Articles