time_nanosleep() function in PHP

The time_nanosleep() function delays execution of the current script for a specified number of seconds and nanoseconds. This function provides more precise timing control than sleep() by allowing nanosecond-level precision.

Syntax

time_nanosleep(sec, nsec)

Parameters

  • sec − The number of seconds to delay the script.

  • nsec − The number of nanoseconds to delay the script (0 to 999,999,999).

Return Value

The time_nanosleep() function returns true on success, or false on failure. If the delay was interrupted by a signal, it returns an associative array with information about the remaining time.

Example

Here's how to use time_nanosleep() to create precise delays −

<?php
   echo date('h:i:s') . "<br>";
   // wait for 1.5 seconds
   time_nanosleep(1, 500000000);
   echo date('h:i:s') . "<br>";
   // wait for 2.5 seconds
   time_nanosleep(2, 500000000);
   echo date('h:i:s');
?>
02:57:04
02:57:06
02:57:08

Microsecond Example

For smaller delays, you can use only nanoseconds −

<?php
   echo "Start: " . microtime(true) . "<br>";
   // wait for 0.1 seconds (100 milliseconds = 100,000,000 nanoseconds)
   time_nanosleep(0, 100000000);
   echo "End: " . microtime(true);
?>

Key Points

  • 1 second = 1,000,000,000 nanoseconds

  • Maximum nanoseconds value is 999,999,999

  • More precise than sleep() or usleep() functions

  • May not work on Windows systems depending on PHP version

Conclusion

The time_nanosleep() function is ideal when you need precise timing control in PHP scripts. Use it for high-precision delays where microsecond or nanosecond accuracy is required.

Updated on: 2026-03-15T07:38:00+05:30

123 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements