Skip to content

usleep()

In this article, we will focus on the PHP usleep() function. We will provide you with an overview of the function, how it works, and examples of its use.

Introduction to the usleep() function

The usleep() function is a built-in function in PHP that was used to pause the execution of a script for a specified number of microseconds. It allowed for delays with very precise timing.

Note: usleep() was deprecated in PHP 8.1 and removed in PHP 8.2. For modern PHP, use time_nanosleep() or time_sleep_until() instead.

The usleep() function takes a single argument, which is the number of microseconds to pause the execution of the script.

How to use the usleep() function

Using the usleep() function is very simple. You just need to call the function and pass the number of microseconds to pause the execution of the script. Here is an example:

How to use the usleep() function?

php
<?php
echo "Sleeping for 500 microseconds...\n";
usleep(500000);
echo "Done sleeping.\n";
?>

In this example, we call the usleep() function with an argument of 500000 for the number of microseconds to pause the execution of the script. This pauses the execution of the script for 500 milliseconds (0.5 seconds). We then output a message to the console indicating that we are sleeping, wait for the specified time, and then output another message indicating that we are done sleeping.

Performance considerations

The usleep() function is lightweight and uses OS sleep calls, so it has negligible CPU overhead. However, the actual pause duration depends on the OS scheduler, meaning sub-millisecond precision is not guaranteed. For higher precision or modern PHP practices, consider time_nanosleep() or time_sleep_until().

Conclusion

In conclusion, the usleep() function is a straightforward way to pause script execution in legacy PHP environments. By understanding its unit requirements, OS-dependent timing behavior, and deprecation status, you can use it effectively for simple delays or migrate to modern alternatives like time_nanosleep() or time_sleep_until().

Practice

What is the purpose of the usleep() function in PHP?

Dual-run preview — compare with live Symfony routes.