Join my Laravel for REST API's course on Udemy 👀

Pause your PHP script for 1 second with sleep()

June 5, 2022  ‐ 1 min read

To pause the execution of your PHP for one second you may use the sleep() function. The sleep() function requires the amount of seconds as its parameter:

<?php

while (true) {
  fetchBitcoinPrice();
  sleep(1); // use `1` to pause one second.
}

The sleep() function only allows for integers as its arguments; thus only full seconds to pause execution. If you need to pause for less then a second or for example 1.5 seconds you should reach for the usleep() function.

sleep() vs. usleep()

Besides the sleep() function PHP provides another function doing something similar; usleep().

Instead of seconds usleep() expects the argument you pass to be in microseconds. Thus to pause for one second that would look like:

<?php

while (true) {
  fetchBitcoinPrice();
  usleep(1000000); // use `1000000` to pause one second.
}