40

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.

Navaneeth Mohan
  • 557
  • 1
  • 5
  • 9
  • Why the rounding? No, there is no overload that takes milliseconds. It's straightforward enough to just do a divide by 1000. – NPras Nov 02 '17 at 03:41
  • `time_nanosleep()` and `time_sleep_until()` are other sleep functions, but I don't see them as being viable alternatives. – Scuzzy Nov 02 '17 at 03:52
  • you can execute an external program with system or exec. These will allow you to use the linux (not sure about windows equivalent) sleep (if loaded) which allows for decimals. I have used this many times to slow down requests to an API where you want more than 1 per second. system('sleep .1'); – DDS Dec 18 '18 at 20:05

1 Answers1

92

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';
Scuzzy
  • 12,186
  • 1
  • 46
  • 46
  • I guess there is no function that accepts milliseconds as the parameter? – Navaneeth Mohan Nov 02 '17 at 03:40
  • No, there is nothing in the documentation for specifically milliseconds, usleep is your only option for non-whole second granualrity. – Scuzzy Nov 02 '17 at 03:41
  • In order to delay program execution for a fraction of a second, use usleep() as the sleep() function expects an int. For example, sleep(0.25) will pause program execution for 0 seconds. – Raskul Jan 19 '23 at 09:07
  • usleep( 1000 * 1000 ); means 1 seconds that equals = sleep(1) – Hakan Feb 22 '23 at 07:59