避免“无响应的脚本”在foreach循环中的消息 [英] Avoiding "Unresponsive Script" message in a foreach loop

查看:107
本文介绍了避免“无响应的脚本”在foreach循环中的消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  for(object in property ){
difficultTask();

$ / code>

我已经看到你可以用 setTimeout 这可以让你周期性地将控制权交还给浏览器;然而,我还没有看到任何能够做到这一点与foreach循环,只有一个索引for循环。此外,这些任务不能异步完成,因为每次迭代都依赖于前一次迭代的结果。



我能想到的一个解决方案是将我的对象分成很多更小的对象,遍历其中的每一个,设置每个之间的超时,但我想看看是否有可能,而不诉诸于此。



是有一种方法可以做到这一点,而不会彻底改变我有我的对象?

解决方案

获取所有的属性到一个数组,然后你可以循环访问一个索引变量和 setTimeout()

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

var index = 0;
函数nextChunk(){
if(index< props.length){
\\ hardTask(object [props [index ++]]));

//在我们让浏览器处理事件之后安排下一块工作
setTimeout(nextChunk,1);
}

}
nextChunk();

您也可以将所有道具放到一个数组中,这是您不需要IE7或IE8兼容性:

  var props = Object.keys(object); 






根据长时间运行的任务的不同,web工作人员也可能是一个有趣的选择,但在IE 10之前不支持IE。

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?

解决方案

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.

这篇关于避免“无响应的脚本”在foreach循环中的消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆