有些时候需要使用异步循环, 整理一下代码,如下
/*
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)
}
本文深入探讨了异步循环的概念及其实现方式,通过具体示例展示了如何利用回调函数来实现异步操作。同时,文章详细介绍了Seajs中轮询机制的应用场景及其实现代码,包括如何在特定条件下触发回调函数。

被折叠的 条评论
为什么被折叠?



