PHP Function Reference

PHP time_nanosleep() Function



The PHP time_nanosleep() function is used to delay the program execution for the specified number of seconds and nanoseconds.

Syntax

time_nanosleep(seconds, nanoseconds)

Parameters

seconds Required. Specify the halt time in seconds. It must be a non-negative integer.
nanoseconds Required. Specify the halt time in nanoseconds. It must be a non-negative integer less than 1 billion.

Return Value

Returns true on success or false on failure.

If the delay was interrupted by a signal, an associative array will be returned with the components:

  • seconds - number of seconds remaining in the delay
  • nanoseconds - number of nanoseconds remaining in the delay

Example: time_nanosleep() example

The example below shows the usage of time_nanosleep() function.

<?php
//this will not work as expected if an
//array is returned (array is returned 
//when the delay is interrupted)
//delaying execution for 0.5 second
if (time_nanosleep(0, 500000000)) {
  echo "Slept for half a second.\n";
}

//this is better way of using this function
//delaying execution for 0.5 second
if (time_nanosleep(0, 500000000) === true) {
  echo "Slept for half a second.\n";
}

//the best way of using this function
//delaying execution for 1.5 second
$nano = time_nanosleep(1, 500000000);

if ($nano === true) {
  echo "Slept for 1.5 seconds.\n";
} elseif ($nano === false) {
  echo "Sleeping failed.\n";
} elseif (is_array($nano)) {
  $seconds = $nano['seconds'];
  $nanoseconds = $nano['nanoseconds'];
  echo "Interrupted by a signal.\n";
  echo "Time remaining: $seconds seconds, $nanoseconds nanoseconds.";
}
?>

The output of the above code will be similar to:

Slept for half a second.
Slept for half a second.
Slept for 1.5 seconds.

❮ PHP Miscellaneous Reference