Share via:

Milliseconds Sleep Function

How to make PHP sleep for milliseconds rather than seconds.

29 views

Edited: 2019-07-13 15:07

In PHP, there is no native function to sleep for mere milliseconds, and we also can not use fractional values in the sleep function. Instead we need to create our own function, using usleep, which is used to sleep for microseconds.

To arrive at the milliseconds, we simply multiply with 1000:

function m_sleep($milliseconds) {
  return usleep($milliseconds * 1000); // Microseconds->milliseconds
}

Multiplying by another 1000 will get us to seconds:

  return usleep($seconds * 1000 * 1000); // Microseconds->milliseconds->seconds

Not that this is needed, since we already got the sleep() function for sleeping for seconds.

Then, to make the script sleep for a specified amount of time, simply call the function:

m_sleep(5000); // 5000 milliseconds = 5 seconds

function m_sleep($milliseconds) {
  return usleep($milliseconds * 1000); // Microseconds->milliseconds
}

Note. A microsecond is one millionth of a second.

Time conversion table

I thought you might find this table useful, since not everyone remembers what the english definitions corresponds to in raw numbers – and who blames you? It is crazy nuts, off your chair, this stuff!

To one second
Nanoseconds 1000000000 (One Billion)
Microseconds 1000000 (One Million)
Milliseconds 1000 (One Thousand)

Comments