Open In App

How to Set Time Delay in PHP ?

Last Updated : 17 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

To set a time delay in PHP, you have several approaches depending on your requirements. The time delay is useful for various purposes like creating a pause in script execution or scheduling tasks.

These are the following different approaches:

Using sleep() Function

The sleep() function pauses the execution of the script for a specified number of seconds. we are going to use that function for showing the time delaying between the printing the lines on the screen.

Example: This example shows the use of sleep() function for time delay.

PHP
<?php
    echo "Start\n";
    sleep(1); // Pauses script execution for 1 seconds
    echo "End\n";
?>

Output:

Start
End

Using usleep() Function

The usleep() function pauses the execution in microseconds. we are going to use that function for showing the time delaying between the printing the lines on the screen.

Example: This example shows the use of usleep() function for time delay.

PHP
<?php
    
    echo "Start\n";
    usleep(500000); // Pauses script execution for 0.5 seconds
    echo "End\n";

?>

Output
Start
End

Using while loop

Use a while loop with a time condition to create a delay. it will first print the line that is outside of the loop then after one second it will print the line inside the loop.

Example: This example shows the implementation of the above-explained approach.

PHP
<?php
    echo "Start\n";
  $start = time();
  while (time() - $start < 1) {
      // Loop for 1 seconds
  }
  echo "End\n";
?>

Output
Start
End

Using DateTime() Object

Create a future timestamp and compare it to the current time. then create a loop that will execute after 1 second exactly.

Example: This example shows the implementation of the above-explained approach.

PHP
<?php
    echo "Start\n";
$delay = new DateTime('+1 seconds');
while (new DateTime() < $delay) {
    // Loop until delay time is reached
}
echo "End\n";
?>

Output:

Start
End

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads