$lastRequestTimestamp = microtime(true);
if (microtime(true) - $lastRequestTimestamp < 1) {
sleep(1);
}
$lastRequestTimestamp = microtime(true);
// now continue with the request ...
... works, but if the difference is even a few milliseconds, it sleeps for 1 second
which is significant considering the number of requests I have to make.
How do I make the script sleep only so much that there's always exactly 1 sec delay between requests, no less no more.
$timeDifferenceSecs = (microtime(true) - $lastRequestTimestamp);
$sleepMicrosecs = (1 - $timeDifferenceSecs)*1000000;
usleep($sleepMicrosecs);
You can use the usleep
function instead, this way you can sleep for microseconds instead of complete seconds.