tags:

views:

290

answers:

3

Is there a way of optimising a jQuery loop when dealing with a fairly large amount of data. The browser tends to lock while the data is being looped through, and anything below IE8 gives a 'script running too slow' message.

I'm just using a jQuery.each(data, function(i, val) to get the field name and value for the field from the database and then automatically populate the field with that value.

The data is taken from a json file that is generated on login.

Any suggestions would be appreciated.

A: 

Push the slow loop iteration to the server and create an eye candy which will keep the user busy while waiting for the result from the server. If the result of looping is not blocking send a callback function to the server and let the user continue its workflow.

Boris Pavlović
+1  A: 

A recent Google Tech Talk from just a few days ago about high-performance JavaScript which mentioned that .each() has huge overhead and why.

http://www.youtube.com/watch?v=mHtdZgou0qU

These things can be pretty involved to fix.

How often do you do this operation? Can you break it up into smaller pieces with setTimeout and give your user a progress bar while you're doing it?

Nosredna
A: 

I've experienced this same problem looping through results, and I don't use the each() function. The blocking behavior, which occurs in an ajax callback function, locks the page, including any 'loading' indicators.

One solution that I have not implemented yet is to have the ajax pull the results in 'chunks' recursively, and displays x number of results at a time (20? 50?). That way the user gets immediate feedback and the perception of locking does not occur.

Maybe something like that could work for you -

jonstjohn
there is a jquery plugin called 'throttle' which does exactly this.
Choog
however, I cant get it to work.
Choog