Search code examples
phpfor-loopdelayed-executiontimedelay

PHP sleep delay


In PHP, I want to put a number of second delay on each iteration of the loop.

for ($i=0; $i <= 10; $i++) {
    $file_exists=file_exists($location.$filename);
    if($file_exists) {
        break;
    }

    //sleep for 3 seconds
}

How can I do this?


Solution

  • Use PHP sleep() function. http://php.net/manual/en/function.sleep.php This stops execution of next loop for the given number of seconds. So something like this

    for ($i=0; $i <= 10; $i++) {
        $file_exists=file_exists($location.$filename);
        if($file_exists) {
            break;
        }
        sleep(3); // this should halt for 3 seconds for every loop
    }