我需要迭代一些大型数组并将它们存储在API调用的主干集合中。如果不使循环导致界面无响应,最好的方法是什么?
由于返回的数据太大,ajax请求的返回也会阻塞。我认为我可以将其拆分并使用setTimeout使其以较小的块异步运行,但有更简单的方法来执行此操作。
我认为Web工作者会很好但是需要更改UI线程上保存的一些数据结构。我已经尝试使用它来执行ajax调用,但是当它将数据返回到UI线程时,仍然有一段时间界面没有响应。
提前致谢
答案 0 :(得分:81)
您可以选择是否有webWorkers:
对于需要与您的应用程序中的DOM或许多其他状态进行交互的代码,您无法使用webWorker,因此通常的解决方案是将您的工作分成块,在计时器上执行每个工作块。使用计时器的块之间的中断允许浏览器引擎处理正在进行的其他事件,并且不仅允许用户输入被处理,而且还允许屏幕绘制。
通常,您可以在每个计时器上处理多个处理器,这比每个计时器只执行一个计时器更高效,更快。此代码使UI线程有机会处理每个块之间的任何挂起的UI事件,这将使UI保持活动状态。
function processLargeArray(array) {
// set this to whatever number of items you can process at once
var chunk = 100;
var index = 0;
function doChunk() {
var cnt = chunk;
while (cnt-- && index < array.length) {
// process array[index] here
++index;
}
if (index < array.length) {
// set Timeout for async iteration
setTimeout(doChunk, 1);
}
}
doChunk();
}
processLargeArray(veryLargeArray);
这是一个概念的工作示例 - 不是同一个函数,而是一个不同的长时间运行过程,它使用相同的setTimeout()
想法来测试具有大量迭代的概率场景:http://jsfiddle.net/jfriend00/9hCVq/ < / p>
您可以将上述内容转换为更通用的版本,调用类似.forEach()
之类的回调函数:
// last two args are optional
function processLargeArrayAsync(array, fn, chunk, context) {
context = context || window;
chunk = chunk || 100;
var index = 0;
function doChunk() {
var cnt = chunk;
while (cnt-- && index < array.length) {
// callback called with args (value, index, array)
fn.call(context, array[index], index, array);
++index;
}
if (index < array.length) {
// set Timeout for async iteration
setTimeout(doChunk, 1);
}
}
doChunk();
}
processLargeArrayAsync(veryLargeArray, myCallback, 100);
也可以让经过的时间成为每个块的指南,并让它在给定的时间间隔内尽可能多地处理,而不是猜测一次有多少块。无论迭代的CPU密集程度如何,这都会自动保证浏览器的响应能力。因此,您可以传入毫秒值(或仅使用智能默认值),而不是传入块大小:
// last two args are optional
function processLargeArrayAsync(array, fn, maxTimePerChunk, context) {
context = context || window;
maxTimePerChunk = maxTimePerChunk || 200;
var index = 0;
function now() {
return new Date().getTime();
}
function doChunk() {
var startTime = now();
while (index < array.length && (now() - startTime) <= maxTimePerChunk) {
// callback called with args (value, index, array)
fn.call(context, array[index], index, array);
++index;
}
if (index < array.length) {
// set Timeout for async iteration
setTimeout(doChunk, 1);
}
}
doChunk();
}
processLargeArrayAsync(veryLargeArray, myCallback);
如果循环中的代码不需要访问DOM,则可以将所有耗时的代码放入webWorker中。 webWorker将独立于主浏览器Javascript运行,然后在完成后,它可以使用postMessage与任何结果进行通信。
webWorker要求将在webWorker中运行的所有代码分离到一个单独的脚本文件中,但它可以运行完成而不用担心阻止浏览器中其他事件的处理而不用担心“无响应的脚本” “在主线程上执行长时间运行的过程时可能出现的提示。
答案 1 :(得分:5)
Here's a demo。它“延迟”迭代1ms并且在该延迟内,它为UI提供了做某事的机会。
function asyncLoop(arr, callback) {
(function loop(i) {
//do stuff here
if (i < arr.Length) { //the condition
setTimeout(function() {loop(++i)}, 1); //rerun when condition is true
} else {
callback(); //callback when the loop ends
}
}(0)); //start with 0
}
asyncLoop(yourArray, function() {
//do after loop
});
//anything down here runs while the loop runs
有web workers和currently proposed setImmediate之类的替代品,其中on IE为{{3}},带有前缀。
答案 2 :(得分:0)
在@ jfriend00上构建,这是一个原型版本:
if (Array.prototype.forEachAsync == null) {
Array.prototype.forEachAsync = function forEachAsync(fn, thisArg, maxTimePerChunk, callback) {
let that = this;
let args = Array.from(arguments);
let lastArg = args.pop();
if (lastArg instanceof Function) {
callback = lastArg;
lastArg = args.pop();
} else {
callback = function() {};
}
if (Number(lastArg) === lastArg) {
maxTimePerChunk = lastArg;
lastArg = args.pop();
} else {
maxTimePerChunk = 200;
}
if (args.length === 1) {
thisArg = lastArg;
} else {
thisArg = that
}
let index = 0;
function now() {
return new Date().getTime();
}
function doChunk() {
let startTime = now();
while (index < that.length && (now() - startTime) <= maxTimePerChunk) {
// callback called with args (value, index, array)
fn.call(thisArg, that[index], index, that);
++index;
}
if (index < that.length) {
// set Timeout for async iteration
setTimeout(doChunk, 1);
} else {
callback();
}
}
doChunk();
}
}
答案 3 :(得分:0)
非常感谢。
我已经更新了代码以添加一些功能。
使用下面的代码,您可以使用数组函数(迭代数组)或地图函数(迭代地图)。
此外,现在有一个参数,该参数用于在块完成时调用的函数(如果需要更新加载消息会有所帮助),以及在处理循环结束时调用的函数的参数(对于在异步操作完成后进行下一步)
//Iterate Array Asynchronously
//fn = the function to call while iterating over the array (for loop function call)
//chunkEndFn (optional, use undefined if not using) = the function to call when the chunk ends, used to update a loading message
//endFn (optional, use undefined if not using) = called at the end of the async execution
//last two args are optional
function iterateArrayAsync(array, fn, chunkEndFn, endFn, maxTimePerChunk, context) {
context = context || window;
maxTimePerChunk = maxTimePerChunk || 200;
var index = 0;
function now() {
return new Date().getTime();
}
function doChunk() {
var startTime = now();
while (index < array.length && (now() - startTime) <= maxTimePerChunk) {
// callback called with args (value, index, array)
fn.call(context,array[index], index, array);
++index;
}
if((now() - startTime) > maxTimePerChunk && chunkEndFn !== undefined){
//callback called with args (index, length)
chunkEndFn.call(context,index,array.length);
}
if (index < array.length) {
// set Timeout for async iteration
setTimeout(doChunk, 1);
}
else if(endFn !== undefined){
endFn.call(context);
}
}
doChunk();
}
//Usage
iterateArrayAsync(ourArray,function(value, index, array){
//runs each iteration of the loop
},
function(index,length){
//runs after every chunk completes, this is optional, use undefined if not using this
},
function(){
//runs after completing the loop, this is optional, use undefined if not using this
});
//Iterate Map Asynchronously
//fn = the function to call while iterating over the map (for loop function call)
//chunkEndFn (optional, use undefined if not using) = the function to call when the chunk ends, used to update a loading message
//endFn (optional, use undefined if not using) = called at the end of the async execution
//last two args are optional
function iterateMapAsync(map, fn, chunkEndFn, endFn, maxTimePerChunk, context) {
var array = Array.from(map.keys());
context = context || window;
maxTimePerChunk = maxTimePerChunk || 200;
var index = 0;
function now() {
return new Date().getTime();
}
function doChunk() {
var startTime = now();
while (index < array.length && (now() - startTime) <= maxTimePerChunk) {
// callback called with args (value, key, map)
fn.call(context,map.get(array[index]), array[index], map);
++index;
}
if((now() - startTime) > maxTimePerChunk && chunkEndFn !== undefined){
//callback called with args (index, length)
chunkEndFn.call(context,index,array.length);
}
if (index < array.length) {
// set Timeout for async iteration
setTimeout(doChunk, 1);
}
else if(endFn !== undefined){
endFn.call(context);
}
}
doChunk();
}
//Usage
iterateMapAsync(ourMap,function(value, key, map){
//runs each iteration of the loop
},
function(index,length){
//runs after every chunk completes, this is optional, use undefined if not using this
},
function(){
//runs after completing the loop, this is optional, use undefined if not using this
});