有些时候需要使用异步循环, 整理一下代码,如下
/*
list 循环数组
run 循环要执行的函数
cb 循环结束调用的函数
*/
function asynLoop(list, run, cb){
var i = 0, len = list.length;
function next(){
if (i<len) {
run(i++, list[i], next);
} else if (typeof cb==='function') {
cb();
}
}
next();
}
/*
循环要执行的函数代码
i 循环数组下标
v 循环数组值
next 下一步函数
*/
function run(i, v, next){
console.log(i);
next();
}
/*
循环结束调用的函数代码
*/
function cb(){
console.log('end');
}
/* 使用示例*/
var list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
asynLoop(list, run, cb);
seajs 中的轮询
function poll(node, callback) { var isLoaded //do node++; if (node>100) { isLoaded = true } setTimeout(function() { if (isLoaded) { // Place callback in here due to giving time for style rendering. callback() } else { poll(node, callback) } }, 1) }function poll(node, callback) {
var isLoaded
//do
node++;
if (node>100) {
isLoaded = true
}
setTimeout(function() {
if (isLoaded) {
// Place callback in here due to giving time for style rendering.
callback()
} else {
poll(node, callback)
}
}, 1)
}
function poll(node, callback) { var isLoaded //do node++; if (node>100) { isLoaded = true } setTimeout(function() { if (isLoaded) { // Place callback in here due to giving time for style rendering. callback() } else { poll(node, callback) } }, 1) } poll(0, function(){ console.log('async is finish!'); })
function poll(node, callback) { var isLoaded //do node++; if (node>100) { isLoaded = true } setTimeout(function() { if (isLoaded) { // Place callback in here due to giving time for style rendering. callback() } else { poll(node, callback) } }, 1) } poll(0, function(){ console.log('async is finish!'); })
function poll(node, callback) { var isLoaded //do node++; if (node>100) { isLoaded = true } setTimeout(function() { if (isLoaded) { // Place callback in here due to giving time for style rendering. callback() } else { poll(node, callback) } }, 1) } poll(0, function(){ console.log('async is finish!'); })
function poll(node, callback) { var isLoaded //do node++; if (node>100) { isLoaded = true } setTimeout(function() { if (isLoaded) { // Place callback in here due to giving time for style rendering. callback() } else { poll(node, callback) } }, 1) }