PHP - sleep() in milliseconds

Navaneeth Mohan picture Navaneeth Mohan · Nov 2, 2017 · Viewed 31.4k times · Source

Does PHP provide a function to sleep in milliseconds?
Right now, I'm doing something similar to this, as a workaround.

$ms = 10000;
$seconds = round($ms / 1000, 2);
sleep($seconds);

I'd like to know whether there is a more generic function that is available in PHP to do this, or a better way of handling this.

Answer

Scuzzy picture Scuzzy · Nov 2, 2017

This is your only pratical alternative: usleep - Delay execution in microseconds

So to sleep for two miliseconds:

usleep( 2 * 1000 );

To sleep for a quater of a second:

usleep( 250000 );

Note that sleep() works with integers, sleep(0.25) would execute as sleep(0) Meaning this function would finish immediatly.

$i = 0;
while( $i < 5000 )
{
  sleep(0.25);
  echo '.';
  $i++;
}
echo 'done';