Sunday, November 17, 2024
Google search engine
HomeLanguagesPHP | usleep( ) Function

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:




<?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');
?>


Output:

06:53:48
06:53:50

Program 2:




<?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');
?>


Output:

06:53:48
06:53:52

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

RELATED ARTICLES

Most Popular

Recent Comments