[英]Long-running loops in JavaScript and UI responsiveness
I had a code that processes a huge JSON array in a "for" loop. 我有一个代码在“ for”循环中处理巨大的JSON数组。
for(var i = 0; item = arr[i]; i++) {
//PROCESS item
}
The issue was with a Firefox browser. 问题出在Firefox浏览器上。 It shows a warning dialog that script is running too long.
它显示一个警告对话框,提示脚本运行时间过长。 The following code was the solution
以下代码是解决方案
//not precise code example, but it's kind of.
delay(arr, 0);
function delay(arr, num) {
//process array by parts with 50 elements in each part
for(var i = 1; i <= 50; i++) {
//PROCESS arr[num];
num += i;
}
if(num < arr.length) {
setTimeout(function() { delay(arr, num); }, 100);
}
}
I wondering if there is a more fabulous way to workaround complete UI freeze and make Firefox to don't show script debug dialog. 我想知道是否有更妙的方法来解决完全UI冻结并使Firefox不显示脚本调试对话框的问题。 Please advise.
请指教。 Thanks
谢谢
如果您使用的是Firefox,则可能正在寻找Web worker ,它允许您生成后台线程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.