PHP | usleep( ) Function

The usleep() function in PHP is an inbuilt function which is used to delay the execution of the current script for specific microseconds. It is similar to the sleep() function which delays execution of the current script for a specified number of seconds, unlike the usleep() function which delays the execution for a specified number of microseconds. The number of microseconds is passed as a parameter to the usleep function and it executes the script according to the mentioned delay passed as a parameter.

Syntax :

usleep(microseconds)

Parameters Used: The usleep() function in PHP accepts one parameter microseconds. It is a mandatory parameter which specifies the delay in the execution of the script.



Return Value: It does not return any value.

Errors and Exceptions:

  1. The usleep() function throws an error if the specified number of seconds is negative.
  2. The usleep() function call consumes CPU cycles and must be used only if necessary. Sleep() function is a better alternative since it doesn’t consume CPU cycles.

Examples:

Input : echo date('h:i:s');
        usleep(2000000);
        echo date('h:i:s');

Output : 06:53:48
         06:53:50

Input : echo date('h:i:s');
        usleep(rand(1000000, 5000000))
        echo date('h:i:s');

Output : 06:53:48
         06:53:52

Below programs illustrate the usleep() function:

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// displaying time
echo date('h:i:s') ;
  
// delaying execution of script for 2 seconds
usleep(2000000);
  
// displaying time again
echo date('h:i:s');
?>

chevron_right


Output:

06:53:48
06:53:50

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// displaying time
echo date('h:i:s') ;
  
// using rand() function to randomly choose a
// value and delay execution of the script
usleep(rand(1000000, 5000000))
  
// displaying time again
echo date('h:i:s');
?>

chevron_right


Output:

06:53:48
06:53:52

Reference :http://php.net/manual/en/function.usleep.php



My Personal Notes arrow_drop_up

I am a technology enthusiast who has a keen interest in programming I am pursuing Engineering in Computer Science from GEU, Dehradun I like to unwind by watching movies and English sitcomsI have a keen interest in music

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.