What is the purpose of calling setTimeout with a delay of 1?

In the Google Drive API Quick Start Guide, the following function is called after loading the client library:

// Called when the client library is loaded to start the auth flow. function handleClientLoad() { window.setTimeout(checkAuth, 1); } 

What is the purpose of calling setTimeout with a delay of 1 like this, instead of calling checkAuth right checkAuth ?

+7
source share
3 answers

Javascript has asynchronous I / O (ajax / requests), as well as setTimeout and setInterval .

One use of the setTimeout run with 1 millisecond (or 0) would be to say that the code should run after the synchronous code follows it. Here is an example

 setTimeout(function(){ alert("World"); },1); alert("Hello"); //alerts "Hello" then "World" 

I wanted my answer to be simple and accurate, if you are interested, there is more detailed information on how setTimeout works in the MDN article about this.

+7
source

Using setTimeout , you allow the page to be interactive until the checkAuth function checkAuth .

Essentially, you are not allowing checkAuth hold the page.

As a side note, the minimum delay specified in the HTML5 specification is 5 ms, so waiting for 1 ms will really wait for 5 ms. If it is important for you to restore this time, you can achieve the same result with a delay of 0 ms using window.postMessage . This was originally intended to handle reciprocal messaging, but a similar effect as setting a timeout with 0ms (which you cannot do as browsers only allow 5ms - or 10ms in some older browsers).

Finally, time is not guaranteed. JavaScript works in a single thread, so when you push something onto a timer, it must wait for the rest of the JavaScript to open before it starts its turn on the thread - it does not start in parallel.

+5
source

setTimeout(function, 1) will execute the function after the current thread has completed. JavaScript in the browser window runs in a single thread. Thus, even if the timeout is 1, it will not work until the current execution is completed. For example, consider the following script:

 window.setTimeout(checkAuth, 1); // long code that takes 5 seconds to complete function checkAuth() { alert("im here!"); } 

In the above example, you will see a warning after 5 seconds.

+1
source

All Articles