FriendOfFuture
FriendOfFuture

Reputation: 2608

What is setTimeout(function(){//dostuff}, 0); actually supposed to do?

Does this pattern:

setTimeout(function(){
             // do stuff
}, 0);

Actually return control to the UI from within a loop? When are you supposed to use it? Does it work equally well in all browsers?

Upvotes: 2

Views: 1366

Answers (5)

ng.mangine
ng.mangine

Reputation: 3007

I've found it very useful for avoiding race conditions when multiple event handlers are fired from the same action.

Upvotes: 0

Mark Cidade
Mark Cidade

Reputation: 100027

It will ansynchronously call the function as soon as any other pending instructions on the thread is done (which is right away if there aren't any) and return control to the UI. You should use it in an event handler where you don't want to run the code while the event is still being propogated*. It works with all browsers.

Upvotes: 1

FlySwat
FlySwat

Reputation: 175663

Think of it as setting up an interupt vector back in the old days.

It won't parallel process that code, but instead it will jump and execute it when event (in this case, a timer finishing) is fired.

Upvotes: 0

Kornel
Kornel

Reputation: 100170

It runs code asynchronously (not in parallel though). The delay is usually changed to a minimum of 10ms, but that doesn't matter.

The main use for this trick is to avoid limit of call stack depth. If you risk reaching limit (walk deep tree structure and plan to do a lot of work on leafs), you can use timeout to start function with a new, empty call stack.

You can also use it to avoid blocking current thread. For example if you don't want <script> element to delay loading of a page:

<script>compute_last_pi_digit()</script> <!-- blocking -->

<script>setTimeout(compute_last_pi_digit,0)</script> <!-- non-blocking -->

Upvotes: 4

user19302
user19302

Reputation:

http://blog.thinkature.com/index.php/2006/11/26/escaping-the-javascript-call-stack-with-settimeout/

Some good info in there. Basically, you are correct and it works on pretty much all browsers. Cool trick.

You would want to use this in the example that the author of the post gave, as well as instances where you need to return execution back to the calling function before your code is executed. Javascript is, apparently, not multi-threaded, but this comes close.

Hope this helps :)

Upvotes: 4

Related Questions