串行执行
var items = [];
for (var i=0;i<10000;i++){
items[i]=i+1;
}
console.log(items);
var results = [];
function async(arg, callback) {
console.log('参数为 ' + arg +' , 1秒后返回结果');
setTimeout(function () { callback(arg * 2); }, 1000);
}
function final(value) {
console.log('完成: ', value);
}
function series(item) {
console.log(item)
if(item) {
async( item, function(result) {
results.push(result);
return series(items.shift());
});
} else {
return final(results[results.length - 1]);
}
}
series(items.shift());
并行执行
var items = [];
for (var i=0;i<10000;i++){
items[i]=i;
}
var results = [];
function async(arg, callback) {
console.log('参数为 ' + arg +' , 1秒后返回结果');
setTimeout(function () { callback(arg * 2); }, 1000);
}
function final(value) {
console.log('完成: ', value);
}
items.forEach(function(item) {
async(item, function(result){
results.push(result);
if(results.length === items.length) {
final(results[results.length - 1]);
}
})
});
并行与串行的结合
var items = [];
for (var i=0;i<1000;i++){
items[i] = i;
}
var results = [];
var running = 0;
var limit = 100;
function async(arg, callback) {
console.log('参数为 ' + arg +' , 1秒后返回结果');
$("#app").append('<div>参数为 '+ arg +' , 1秒后返回结果</div>')
window.scrollTo(0,document.body.scrollHeight);
setTimeout(function () { callback(arg * 2); }, 3000);
}
function final(value) {
console.log('完成: ', value);
$("#app").append('<div>完成 '+ value.toString() +'</div>')
}
function launcher() {
while(running < limit && items.length > 0) {
var item = items.shift();
async(item, function(result) {
results.push(result);
running--;
if(items.length > 0) {
launcher();
} else if(running == 0) {
final(results);
}
});
running++;
}
console.log("当前执行任务数量:"+running+" 剩余任务数量:"+items.length);
}
launcher();