Processor-Intense Javascript

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.
}&#91;/js&#93;

&#91;js&#93;// 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).

Posted: April 13th, 2005


Subscribe for email updates

3 Comments (Show Comments)



Comments are closed.
Comments are automatically turned off two weeks after the original post. If you have a question concerning the content of this post, please feel free to contact me.


Secrets of the JavaScript Ninja

Secrets of the JS Ninja

Secret techniques of top JavaScript programmers. Published by Manning.

John Resig Twitter Updates

@jeresig

Infrequent, short, updates and links.