Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

javascript - 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 with setTimeout which can allow you to periodically return control to the browser; however, I haven't seen any that are able to do this with a foreach loop, only a for loop with an index. Additionally, these tasks cannot be completed asynchronously since each iteration depends on a result from the previous iteration.

One solution I can think of is to split up my object into a lot of smaller objects and iterate through each of them, setting a timeout in between each one, but I'd like to see if this is possible without resorting to that.

Is there a way to do this without drastically changing how I have my objects?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 in object) {
    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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...