Jakob
Jakob

Reputation: 2746

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

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?

Upvotes: 11

Views: 1258

Answers (3)

Fenton
Fenton

Reputation: 250892

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.

Upvotes: 7

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276296

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

Upvotes: 10

Tarandeep Gill
Tarandeep Gill

Reputation: 1536

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.

Upvotes: 2

Related Questions