Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 803
FriendOfFuture Avatar asked Jan 21 '26 21:01

FriendOfFuture


1 Answers

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 -->
like image 146
Kornel Avatar answered Jan 24 '26 11:01

Kornel