Home » Php » javascript – Is there a set time out equivalent in php?

javascript – Is there a set time out equivalent in php?

Posted by: admin July 12, 2020 Leave a comment

Questions:

Is there a PHP equivalent to setting timeouts in JavaScript?

In JavaScript you can execute code after certain time has elapsed using the set time out function.

Would it be possible to do this in PHP?

How to&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';
}

Answer:

PHP is single-threaded, and in general PHP is focused on the HTTP request cycle, so this would be tricky to allow a timeout to run code, potentially after the request is done.

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

Answer:

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 will only be called after a tickable PHP statement. So if you try to call a function 10 times per second, but you call sleep(10), you’ll get 100 executions of your tick function in a batch after the sleep has finished.

Note that there is an additional parameter to setInterval that limits the number of times it is called. setTimeout just 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 if that would even be possible unless there was a master tick function that monitored and unregistered them.

I didn’t attempt to implement anything like that because this is not how PHP is designed to be used. It’s likely that there’s a much better way to do whatever it is you want to do.

Answer:

Without knowing a use-case for your question it’s hard to answer it:

  • If you want to send additional data to the client a bit later you can do a JS timeout on the client side with a handler that will make a new HTTP request to PHP.
  • If you want to schedule some task for a later time you can store that in a database and poll the DB in regular intervalls. It’s not the best peforming solution but relatively easy to implement.