I have a variable ($i) starts from 0 to 9. It keeps increasing ($i++) in a loop until it reaches 9, when it reaches 9 it sets back $i to 0. I want to run this loop for 2 seconds only and then get the final number where it stopped after 2 seconds. So I wrote the following code:
$now = time();
$counter = 0;
while ($now + 2 > time()) {
$counter++;
if($counter == 9)
$counter = 0;
}
echo 'Counter: '.$counter;
However this is inaccurate, every time it runs for 2 seconds, number is different. How can I use usleep(2000000); which I read is more accurate in while() or for() loop and break the loop and print the $counter number with accuracy.