When authoring the new Schedule Maker application, one problem that I came across was the concept of processor-intensive Javascript code. The problem is that when a piece of Javascript runs for too long, it freezes the browser and does not allow the user to enter any input. This issue usually occurred when running a function that iterates a large number of times while doing lots of itense DOM processing. Now, I figured out a neat hack (which I’m sure may be common knowledge to some) to stop this from happening, observe:
// This will block the browser and cause it to freeze for ( var i = 0; i < 100; i++ ) { // Do lots of DOM processing, etc. }[/js] [js]// This will go slower - but will not block the browser foo( 100 ); function foo( count ) { // Do lots of DOM processing, etc. if ( count > 0 ) setTimeout( "foo(" + count - 1 + ");", 10 ); }
The essential difference is that there is now a 10 millisecond pause inbetween processing the next portion of a loop, giving the browser some breathing room to allow user interaction. Now, the bad part: It doesn’t actually take 10 millisecond, it seems as if the browser can’t handle a timeout that small. I haven’t run any tests yet to figure out what the number actually is, but it’s hard to say. The nice thing about this though is that you can update the browser with a status while you’re processing, giving the end-user a more interactive experience (as opposed to a multi-second freeze).
Bob Aman (April 21, 2005 at 9:07 am)
Nice. Have you tried this with Opera? I’m pretty sure Opera has a single-threaded Javascript interpreter, and I think it does something funny with the setTimeout function. You might want to check that.
Sean Graham (April 26, 2005 at 8:05 pm)
I ran into similar problems while working on our mozilla based software at Rovia… Before Adam and I rewrote our whole UI using XUL and XPCOM, everything was HTML and JS, and we had similar problems, and came to similar conclusions… :)
I honestly can’t remember if the same problems existed once we started using XPConnect JS stuff…. I BELIEVE that the JS context from the HTML view in our application was seperate from the context used for our app logic, but honestly time has faded those memories..
mike (October 8, 2007 at 7:56 pm)
i have this problem now,
i need to for loop and create option elements inside select element.
problem is i have 5000 select options that need to be created and it causes the browser to freeze for like 1 second. i put a loading gif to be switched to display: block before the loop, but the browser doesn’t even process it because of the loop which is after it =(
i tried adding a setTimeout(function() blah, 2), and it made it even worse. it just crashed the browser