简体   繁体   中英

Javascript setTimeout timing reliability

I have recently started exploring Javascript in more detail, and how it executes within the browser. Specifically, the setTimeout function.

My understanding is that calling setTimeout(foo,x) will pass a handle to foo to be executed after x milliseconds. How reliable is this timing? Obviously if another long-running script is still executing after x milliseconds then the browser won't be able to call foo, but can I be absolutely certain that setTimeout(foo,101) will always be executed after setTimeout(foo,100) ?

First of all, the timeout is in miliseconds, therefor 1 sec = 1000 ms. consider that. you can always be sure that delay of 1001 will be later than 1000. BUT You must remember that if the 2nd methods relay on changes of the first method it doesnt mean it will work good. the first methods can take for reasonable time of 3ms (not a complicated one) and the 2nd one can start only 1 ms after the first one causing your reliability on the first method to fail. i would suggest not to use this feature but in some rare cases.

you can tag me in this answer comment for your specific case and i can suggest the right way to work it out.

Most browsers use single thread for UI and JavaScript, which is blocked by synchronous calls. So, JavaScript execution blocks the rendering.

Events are processed asynchronously with the exception of DOM events.

but setTimeout(function(),1000) trick is very useful. It allows to:

Let the browser render current changes. Evade the “script is running too long” warning. Change the execution flow. Opera is special in many places when it comes to timeouts and threading.

So if another function is executing it will handle it by running in parallel.

another thing to setTimeout(function(),1000) her time is in millisecond not in seconds.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM