javascript异步循环

有些时候需要使用异步循环, 整理一下代码,如下

/*

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)
}  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值