Is there a set time out equivalent in php?

后端 未结 4 1022
不思量自难忘°
不思量自难忘° 2020-12-20 16:09

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.

4条回答
  •  情书的邮戳
    2020-12-20 16:57

    This is ugly, but basically works:

     $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.

提交回复
热议问题