11

In the quickstart guide for the Google Drive API, the following function is called once the client library has loaded:

// 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 just calling checkAuth immediately?

Jakob
  • 2,588
  • 5
  • 27
  • 34

3 Answers3

10

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

One use of running setTimeout with 1 milisecond (or 0) would be to tell that code to be run after the synchronous code following it. Here is an example

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

//alerts "Hello" then "World"

I wanted to keep my answer simple and to the point, if you're interested, there is more details about how setTimeout works in the MDN article about it

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
7

By using setTimeout you allow the page to be interactive before the checkAuth function completes.

Essentially, you are preventing the checkAuth from holding up the page.

As a side note, the minimum delay specified in the HTML5 specification is 5ms, so a wait of 1ms will actually be a wait of 5ms. If it is important for you to reclaim that time, you can achieve the same result with a 0ms delay by using window.postMessage. This was originally designed to handle cross-origin communication, but has a similar effect as setting a timeout with 0ms (which you can't do as browsers only allow 5ms - or 10ms in some older browsers).

Lastly, the timing is not guaranteed. JavaScript runs on a single thread, so when you push something out onto a timer it must wait for an opening in the execution of the rest of the JavaScript before it gets to take its turn on the thread - it doesn't run in parallel.

Fenton
  • 241,084
  • 71
  • 387
  • 401
2

setTimeout(function, 1) will make function run after the current thread of execution is complete. JavaScript in a browser window runs in a single thread. So, even if the timeout is 1, it won't run until after the current execution is over. for example consider the following script:

window.setTimeout(checkAuth, 1);

// long code that takes 5 seconds to complete


function checkAuth() {
    alert("i m here!");
}

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

Tarandeep Gill
  • 1,506
  • 18
  • 34
  • In javascript (with the exception of node.js child processes/threads_a_gogo, and web workers) there is only one thread of execution. – Benjamin Gruenbaum Feb 06 '13 at 23:24
  • @BenjaminGruenbaum Well I was sure that it runs in a single thread at least in the browser, and that's what the OP is concerned about. But thanks for the info. – Tarandeep Gill Feb 06 '13 at 23:26