views:

290

answers:

5

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?

+4  A: 

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 :)

nlaq
Thanks, I was hopping this question would spawn a couple good links.
Sasha Sklar
+1  A: 

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.

Mark Cidade
+4  A: 

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 -->
porneL
A: 

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.

FlySwat
A: 

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

ng.mangine