Skip to content Skip to sidebar Skip to footer

Avoiding "unresponsive Script" Message In A Foreach Loop

I am writing a javascript program with a very long-running foreach loop like the following: for (property in object) { difficultTask(); } I've seen that you can do some things

Solution 1:

Get all the properties into an array and then you can cycle through the array with an index variable and a setTimeout():

var props = [];
for (property inobject) {
    props.push(property);
}

var index = 0;
function nextChunk() {
    if (index < props.length) {
        difficultTask(object[props[index++]]));

        // schedule the next chunk of work after we let the browser process events
        setTimeout(nextChunk, 1);
    }

}
nextChunk();

You could also get all the props into an array with this is you don't need IE7 or IE8 compatibility:

var props = Object.keys(object);

Depending upon what the long running task does, web workers could also be an interesting option, but no support in IE until IE 10.

Solution 2:

I think that this snippet can achieve what you want:

function executeAndSleep(array,currentPos,step,sleepTime){
   for(var i = currentPos;i<currentPos+step&&i<array.length;i++){
      //execute your magic here
   }
   if(currentPos+step<= array.length){
       setTimeout(function(){
             executeAndSleep(array,currentPos+step,step,sleepTime);
        },sleepTime);
   }
}

you can see it working here http://jsfiddle.net/victorrseloy/3utwF/

Solution 3:

This sounds like a useful point to use web workers. They allow concurrent execution of javascript code. You might want to read the introduction to webworkers. The article is quite old (might now be outdated in some points), but still good.

The browser support is now pretty good. If you need browser support for old IEs, you can use a polyfill, so you can start working with web workers right now.

Post a Comment for "Avoiding "unresponsive Script" Message In A Foreach Loop"