phpfor-loopsleepcontinueusleep

PHP sleep() For Specific Block of Code


I need to delay the continue statement of a loop I am running by a certain number of microseconds. However, I want the rest of the loop to run, and then I just want it to stop running and continue when the time is up, even if some things in the loop are left undone. I know this code does not work, but this is what I am envisioning:

for ($_x = 0; $_x < 10; $_x++){
    usleep (1000){
        continue;
    }

    // ... do other stuff here until timer is up

    // when the timer runs out, continue to the next iteration
}

Thanks in advance.


Solution

  • here's what you want. i've converted to to sleep 1 instead of usleep to prove it works, but if you switch it back it accomplishes what you want. you're welcome.

    function microtime_float()
    {
        list($usec, $sec) = explode(" ", microtime());
        return ((float)$usec + (float)$sec);
    }
    
    for ($_x = 1; $_x < 11; $_x++) {
        $_m = microtime_float();
        $_v = sleep(1);
        $_n = microtime_float();
        do{
            //script here
            echo "<hr></br>".$_m."</br>".$_n ."</br>" .$_x;
        }
        while($_v);
    }
    

    the output

    1396497686.9354 1396497687.9356 1

    1396497687.9357 1396497688.9363 2

    1396497688.9364 1396497689.937 3

    1396497689.9371 1396497690.9381 4

    1396497690.9381 1396497691.9392 5

    1396497691.9393 1396497692.9398 6

    1396497692.9399 1396497693.9406 7

    1396497693.9406 1396497694.9415 8

    1396497694.9415 1396497695.9424 9

    1396497695.9424 1396497696.9427 10