避免“无响应脚本"foreach 循环中的消息 [英] Avoiding "Unresponsive Script" message in a foreach loop
问题描述
我正在编写一个具有非常长的 foreach 循环的 javascript 程序,如下所示:
I am writing a javascript program with a very long-running foreach loop like the following:
for (property in object) {
difficultTask();
}
我已经看到您可以使用 setTimeout
做一些事情,它可以让您定期将控制权返回给浏览器;但是,我还没有看到任何能够使用 foreach 循环执行此操作的工具,只有带有索引的 for 循环.此外,这些任务不能异步完成,因为每次迭代都依赖于前一次迭代的结果.
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?
推荐答案
把所有的属性放到一个数组中,然后你可以用一个索引变量和一个setTimeout()
来循环遍历这个数组:
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();
您也可以将所有道具放入一个数组中,因为您不需要 IE7 或 IE8 兼容性:
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);
<小时>
根据长时间运行的任务的作用,网络工作者也可能是一个有趣的选择,但在 IE 10 之前不支持 IE.
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屋!