JQuery: Keeping the UI Responsive During Slow Page Loads With The Event Queue

Let's say we have some really slow operation that works like this:

$("#container").empty(); $(giantArray).each(function(i, element){      verySlowRenderOperation(element).appendTo($("#container"); });

It's possible that this will make the page lock up while the above routine executes.  Most web browsers will even become unresponsive while this happens.  The most popular way to solve this problem is to use setTimeout.  The problem with setTimeout is that things might occur out of order, but the above code should maintain order in some way.  Here's a fairly elegant solution to the problem that uses jQuery's built in function queue to delay processing of any queue of arbitrary functions in order.  We can create a 1ms pause between each call which will free up the page to process other things and do all of our work in a separate thread.

$("#container").clearQueue(); //Prevent race conditions if a previous run is still pending. $("#container").empty(); $(giantArray).each(function(i, element){     $("#container").delay(1).queue(function(){         verySlowRenderOperation(element).appendTo($("#container");         $(this).dequeue();     }); });

More information can be found in jQuery's documentation on queue() and delay().

No comments

Post a Comment