I have read the post here about using setTimeout() during intensive DOM processing (using JavaScript), but how can I integrate this function with the below code? The below code works fine for a small number of options, but when the number of options gets too big my ‘please wait’ animated GIF freezes while the local JavaScript is processing. Thanks!
function appendToSelect() { $('#mySelect').children().remove() ; $('#mySelect').html( '<option selected value='' + obj.data[0].value + ''>' + obj.data[0].name + '</option>' ); var j = 1 ; for (var i = 1; i < obj.data.length; i++) { $('#mySelect').append( '<option value='' + obj.data[i].value + ''>' + obj.data[i].name + '</option>' ); } }
Here is a solution:
Not as elegant as @Borgar’s solution, but you get the idea. Basically, I am doing the same thing, but all in your one function rather than breaking it into a higher-order function like he does. I like his solution, but if you don’t, perhaps this will work for you.
EDIT: For those that don’t immediately see it, one of the main differences between this solution and @Borgar’s is that this solution allows you to set the size of the ‘chunks’ of data that is processed between each timeout. @Borgar’s times-out after every single member of the array is processed. If I get time, I will try to create a higher-order function to handle this so it is more elegant. No promises though! 😉
EDIT: So, here is my adaptation of @Borgar’s solution, which allows for setting a ‘chunk’ size and configuring the timeout value more easily:
Hope that helps – I think this combines the best of both solutions. Notice, the second anonymous function no longer uses the index value, but simply passes in the entire object (with the value and name properties); that makes it a bit cleaner, since the index of the current object really isn’t usually that useful when iterating over things, IMO.
I am sure there are still things that could be done to make this even better, but that is left as an exercise for the reader. 😉