2

I have been changing how the javascript on my website works to make it more responsive. I have added lines like this:

setTimeout(function () {doTasks();}, 0);

Is it always enough to have a timeout of 0? Are there any browsers where this trick will not work?

Oliver
  • 11,297
  • 18
  • 71
  • 121
  • I'm not sure what this trick achieves in the first place? – Pekka Feb 07 '12 at 11:16
  • I think this is supposed to perform the tasks in the background. – Stefan Paul Noack Feb 07 '12 at 11:17
  • It breaks up long functions, so instead of one function that runs for 10 seconds and freezes the browser, there are 100 functions that run for 100ms so that the browser is still responsive. In theory. – Oliver Feb 07 '12 at 11:17
  • JavaScript isn't multithreaded so I don't see how this would shorten the length of execution. – Ash Burlaczenko Feb 07 '12 at 11:22
  • @AshBurlaczenko It's not about making the code execute faster, its about making the browser more responsive. If you have a big chunk of javascript that runs for several seconds, some browsers will freeze up while it runs. Also, some browsers, such as Safari for the iphone, refuse to run javascript if it takes too long to execute. This trick fixes that, hopefully. I want to know if it will work in all browsers. – Oliver Feb 07 '12 at 11:32
  • According to http://stackoverflow.com/a/779785/393908 it just lets the html rendering catch up with the javascript – Ash Burlaczenko Feb 07 '12 at 11:34

1 Answers1

4

Yes, this works in every browser.

But note that the actual delay will be around 10 ms.

For those who don't understand. This will empty the call stack as the callback function will be called asynchronously. Plus it gives the program some time to "breathe" and do stuff like firing other events or updating the UI.

J. K.
  • 8,268
  • 1
  • 36
  • 35