用setTimeout实现循环,并增加最小循环周期配置

console.log(
  "实现一个循环,若循环内部异步函数执行时间大于3秒,则在所有内部异步函数执行完成后再次执行循环;否则3秒执行循环"
);

function coreFun(time) {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log(`sleep ${time}`);
      resolve();
    }, time);
  });
}

let coreMission = async () => {
  for (let i = 0; i < 3; i++) {
    await coreFun(2000);
  }
};

let asyncFun = async (minTime) => {
  let oneCycleStart = Date.now();
  let promise3 = new Promise((resolve, reject) => {
    setTimeout(resolve, minTime);
  });
  let promise1 = coreMission();
  await Promise.all([promise1, promise3]);

  let oneCycleEnd = Date.now();
  console.log(`oneCycleEnd interval`, oneCycleEnd - oneCycleStart);
  setTimeout(() => {
    asyncFun(minTime);
  }, minTime);
};

(async (minTime) => {
  let cycleStart = Date.now();
  await asyncFun(minTime);
  let cycleEnd = Date.now();
  console.log(`cycle interval`, cycleEnd - cycleStart);
})(3000);


你可能感兴趣的:(nodejs,javascript)