PHP - sleep() in milliseconds [duplicate]
Asked Answered
O

1

45

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.

Outdate answered 2/11, 2017 at 3:29 Comment(3)
Why the rounding? No, there is no overload that takes milliseconds. It's straightforward enough to just do a divide by 1000.Thrasonical
time_nanosleep() and time_sleep_until() are other sleep functions, but I don't see them as being viable alternatives.Latinist
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');Fumigator
L
98

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';
Latinist answered 2/11, 2017 at 3:31 Comment(8)
I guess there is no function that accepts milliseconds as the parameter?Outdate
No, there is nothing in the documentation for specifically milliseconds, usleep is your only option for non-whole second granualrity.Latinist
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.Rodrigorodrigue
usleep( 1000 * 1000 ); means 1 seconds that equals = sleep(1)Append
So if I need exactly a pause of 1.5 seconds, i have to write sleep(1); usleep(500000); together? That's so crappyNailbiting
@Nailbiting I'd write usleep(1500000), or try to figure out a better way where no sleep is required.Latinist
@Latinist Yes I wanted to, until I saw this in the PHP docs: "Note: Values larger than 1000000 (i.e. sleeping for more than a second) may not be supported by the operating system. Use sleep() instead."Nailbiting
Ahhh, good times PHPLatinist

© 2022 - 2024 — McMap. All rights reserved.