Two functions are mainly used in PHP to delay the execution of the script for some time. These are usleep() and sleep(). The usleep() function is used to delay the execution of the script for specific microseconds. This function can throw an exception if the negative microseconds value is provided. This function consumes the CPU cycle also when called. How this function can be used in PHP has shown in this tutorial.

Syntax:

The syntax of this function is given below.

void usleep (int microseconds)

This function takes the microseconds value as function arguments used to delay the script where this function is used. This function returns nothing. The different uses of this function are shown below by using various examples.

Example-1: Use of usleep() to wait 5 seconds

The following example shows how usleep() can be used to set the delay for 5 seconds in the script. Create a PHP file with the following script. date() function is used in the script to read the current date and time. usleep() function is called after executing the first date() function. 5 seconds is equal to 5000000 microseconds. So, 5000000 is used as the usleep() argument value to set the delay for 5 seconds. Next, the date() function is called again.

<?php

//Display the current date and time

echo date(‘d F, Y h:i:s a’).
;

//Print the message

echo “Waiting for 5 seconds…
;

//Delay thew execution of script for 5 seconds

usleep(5000000);

//Display the current date and time

echo date(‘d F, Y h:i:s a’).
;

?>

Output

The script will wait for 5 seconds after executing it from the server. The output shows that the script started the execution at 05:32:05 am, and the script terminated at 05:32:11 am. So, 5 seconds have passed before displaying the output.

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/01/echo/image3-15.png" data-lazy- height="183" src="data:image/svg xml,” width=”1086″>

Example-2: Use of usleep() to wait for random times

The following example shows how usleep() and rand() functions can be used to set the delay for the random number of times. Create a PHP file with the following script. The first date() function of the script will read the current system time. Next, the rand() function is used to generate a number between 1000000 and 4000000, and the generated random value will be used as the argument value of the usleep() function. The generated random number will be divided by 1000000 and utilized in the round() function to get the delay time in seconds. The second date() function is used to read the time value after executing the usleep() function.

<?php

//Display the current time

echo date(‘h:i:s a’).
;

//Set the random microseconds value

$delay = rand(1000000,4000000);

//Delay the execution of script for defined seconds

usleep($delay);

//Convert the microseconds into seconds

$seconds = round($delay/1000000);

//Print the message

echo “Waiting for $seconds seconds…
;

//Display the current time

echo date(‘h:i:s a’).
;

?>

Output

According to the following output, the script waited for 4 seconds after executing in the server. The output shows that the script started the execution at 05:35:40 am, and the script terminated at 05:35:44 am. So, the script has been delayed for 4 seconds.

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/01/echo/image4-13.png" data-lazy- height="184" src="data:image/svg xml,” width=”1090″>

Example-3: Repeat the script after 2 seconds

The following example shows how the same script can be repeated after 2 seconds of delay based on the user’s selection. Create an HTML file named form1.html with the following script to take the value of x and n.

form1.html

<html>

<head>

<title>Use of usleep() function</title>

</head>

<body>

    </form method=“post” action=“power.php”>

        Enter the value of x :  <br />

        Enter the value of n :  <br />

        </input type=“submit” name=“submit” value=“Submit” />

    </form>

</body>

</html>

The form’s data will be submitted into the PHP file named power.php to calculate the x to the power n. Create the power.php file with the following script. It will check the field values of the HTML form are set or not. If the values are correctly submitted, then the x to the power n will be calculated, and the script will wait for 2 seconds. An alert box will appear after 2 seconds. Another form with a checkbox will appear to ask the user to repeat the same task after clicking the OK button of the alert box.

power.php

<?php

//Check the values of x and n are set or not

if(isset($_POST[‘x’]) && isset($_POST[‘n’]))

{

    $flag = false;

    $x = $_POST[‘x’];

    $n = $_POST[‘n’];

    //Calculate the x to the power n

    $result = pow($x,$n);

    //Print the result

    echo $x to the power $n is $result
;

    //Display the form to repeat the task again or not

    echo

    Do the task again

    ‘

;

    //Wait for two seconds

    usleep(2000000);

    //Display the alert

    echo “alert(‘Waited for 2 seconds…’)”;

}

else

{

    if(!isset($_POST[‘ok’]))

        include(‘form1.html’);

    else

    {

        //Repeat the task again if the checkbox is on

        if(isset($_POST[‘task’] )){

            if($_POST[‘task’] == ‘on’)

                include(‘form1.html’);

            else

                die(“The script is terminated.”);

        }

        else

            die(“The script is terminated.”);

    }

}

?>

Output

The following form will appear after running the PHP script from the server. In the output, 4 is set for the value of x, and 3 is set for n.

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/01/echo/image6-10.png" data-lazy- height="205" src="data:image/svg xml,” width=”1089″>

After submitting the form, the script will calculateand wait for 2 seconds before displaying the alert box.

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/01/echo/image5-12.png" data-lazy- height="401" src="data:image/svg xml,” width=”1090″>

The following form will appear to select the option to display the previous form again to calculate the power of another value of x and n after pressing the OK button.

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/01/echo/image2-17.png" data-lazy- height="176" src="data:image/svg xml,” width=”1087″>

If the user presses the OK button without selecting the checkbox, the script will be terminated by displaying the following message.

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/01/echo/image1-17.png" data-lazy- height="140" src="data:image/svg xml,” width=”1089″>

Conclusion

When the PHP script requires delay for a specific period for programming purposes, then the usleep() function can be used to do the task. The usleep() function has been explained in this tutorial by using various examples to help the readers know how to generate a delay in the script. Sleep () is another built-in function of PHP to develop in the script.

About the author

<img alt="Fahmida Yesmin" data-lazy-src="https://kirelos.com/wp-content/uploads/2021/01/echo/channel-logo-150×150.jpg6003c2748cd9e.jpg" height="112" src="data:image/svg xml,” width=”112″>

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.