Home > Articles

  • Print
  • + Share This

Halting Program Execution

Problem

You want to stop program execution for a couple of seconds or microseconds.

Solution

Use PHP's sleep() and usleep() functions, depending on how long you want your program to stop execution:

<?php
print "Hello World";
sleep(5); // Sleep 5 seconds
print "This was done 5 seconds later";
usleep(70); // Sleep 70 microseconds
print "This was done 5 seconds and 70 microseconds after the first Hello
    World";
?>

Discussion

The sleep() and the usleep() functions both make system calls to the sleep() function. However, the usleep() function converts the sleep time, like so:

sleep((int) (useconds / 1000));

Sleeping is sometimes useful if you are working with sockets, or you are writing a daemon (CGI version of PHP only) that performs operations at regular intervals of time. (This usually can and should be done with cron.)

  • + Share This
  • 🔖 Save To Your Account

Related Resources

There are currently no related titles. Please check back later.