Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pause a script just for a fraction of a second in PHP using the SLEEP() function?

Tags:

php

time

sleep

wait

sleep(1);   #waits/sleeps for one second then continue running the script

Q1. How to make this 1/100 of a second? which of these work: 0,01 or 0.01 or .01 ?

Q2. What are alternatives? wait(); or snap(); ?? how do they differ (more/less precise)?

like image 853
Sam Avatar asked Mar 27 '11 01:03

Sam


2 Answers

Q1. How to make this 1/100 of a second? which of these work: 0,01 or 0.01 or .01 ?

None of the above!

usleep is what you want for fractions of a second. usleep(100000) will sleep for one tenth of one second.

Your other options are time_nanosleep which takes both seconds and freaking nanoseconds (one billion of which are one second), and time_sleep_until, which will sleep until a particular unix timestamp has been reached.

Be aware that your system might not have millisecond resolution, no less nanosecond resolution. You might have trouble sleeping for precisely tiny, tiny amounts of time.

like image 127
Charles Avatar answered Oct 08 '22 23:10

Charles


Late answer... but you can use time_nanosleep(), i.e:

To sleep for 1/10 of a second (0.1):

time_nanosleep(0, 100000000);

To sleep for 1/100 of a second (0.01):

time_nanosleep(0, 10000000);

To sleep for 1/1000 of a second (0.001):

time_nanosleep(0, 1000000);
like image 34
Pedro Lobito Avatar answered Oct 09 '22 00:10

Pedro Lobito