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

别来无恙 提交于 2020-03-10 04:04:21

问题


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)?


回答1:


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.




回答2:


Use usleep in which you can pass in microseconds,

so for your case you can call usleep(10000) to sleep for 1/100 of a second.




回答3:


What you are looking for is usleep() or time_nanosleep().

As for your second question, all these methods come with a high level of precision however I would advise you to test on your specific system if it's critical.




回答4:


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);


来源:https://stackoverflow.com/questions/5446607/how-to-pause-a-script-just-for-a-fraction-of-a-second-in-php-using-the-sleep-f

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!