How to run while loop for N seconds in PHP

2 Answers

0 votes
$starttime = time();
$seconds = 3;
$endtime = $starttime + $seconds;

while ($starttime < $endtime) {
    sleep(1);
    $starttime = time();
    echo date("Y-m-d H:i:s", $starttime) . "\n";
}



/*
run:

2024-10-11 08:43:38
2024-10-11 08:43:39
2024-10-11 08:43:40

*/

 



answered Oct 11, 2024 by avibootz
0 votes
$startTime = time(); // Get the current time
$duration = 3; // Duration in seconds

while ((time() - $startTime) < $duration) {
    sleep(1); // Sleep for 1 second 
    echo "Loop is running..." . "\n";
}


/*
run:

Loop is running...
Loop is running...
Loop is running...

*/

 



answered Oct 11, 2024 by avibootz

Related questions

1 answer 118 views
1 answer 113 views
1 answer 118 views
1 answer 108 views
2 answers 161 views
2 answers 157 views
1 answer 96 views
96 views asked Oct 11, 2024 by avibootz
...