nodejs的sleep实现

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/m0_37843473/article/details/87620302

var mycb = function mycb(arg) {
  console.log(`in my cb!! arg:${arg}`);
  return arg;
}

async function timercall(cb, arg, inteval) {
  let p = new Promise((resolve, reject) => {
    setTimeout(() => {
      //先调用cb
      let ret = cb(arg);
      //返回
      resolve({
        callback: cb,
        arg,
        ret
      });
    }, inteval);
  });
  return p;
}

//循环sleep 2S 的方法:
async function loopedcall(times) {
  var interval = 2000;
  for (var i = 0; i < times; i++) {
    var p = await timercall(mycb, i, interval);
    console.log(`${i}: call: cbname: ${p.callback.name}, arg: ${p.arg}, ret: ${p.ret}`);

    if (p.ret == 3) {
      console.log(`${i}: call end, i will break`);
      break;
    }
  }
}


loopedcall(6);
展开阅读全文

没有更多推荐了,返回首页