首页 > 解决方案 > 每 5 秒对特定数字重复一次操作,并且必须检查整个数组

问题描述

我必须检查这种安排中的所有值。整个数据分布变量称为“订阅用户”,我想知道当您尝试每 5 秒执行 10 次操作时是否有问题或更好的方法来创建以下逻辑。

let loopCount = 10;
let NumberOfBundle = Math.ceil(subscribingUser.length / loopCount); // 176
let restOfBundle = subscribingUser.length % loopCount; // 8

let bundleCount = 1;
let start = 0;
let bundleInterval = setInterval(async() => {

   for(let i = start; i < loopCount; i++) {
       //Perform 10 specific actions ...
       await subscribingUser[i] ~
   };

   //Send all 10 and raise the BundleCount
   bundleCount += 1;
   start = loopCount;

   if (bundleCount == NumberOfBundle && restOfBundle != 0) {
       loopCount = restOfBundle - 1;
   } else {
       loopCount = loopCount * bundleCount;
   }

   if(bundleCount == NumberOfBundle + 1) {
       clearInterval(bundleInterval);
   }

}, 5000);

标签: javascriptalgorithmsetinterval

解决方案


  1. 首先,考虑避免
for(...){
  await ...
}

因为您将按顺序执行您的工作,这否定了使用捆绑包的兴趣(并行处理捆绑包中的每个用户)

而是针对

await Promise.all(users.map(u => doSomethingWithUser(u)))
  1. 关于逻辑

您可以考虑将膨胀的东西从您的“客户”代码中分离出来

function bulker(arr, n) {
  return {
    async forEach (fn, binding) {
      for(let i = 0; i < arr.length; i += n) {
        await fn.call(binding, arr.slice(i, i + n), i, i  +n >= arr.length)
      }
    }
  } 
}

const doSomethingWithUser = u => {
  console.log('go', u);
  return Promise.resolve(u)
}

;(async _=> {

  //choose whenever you want to wait or not
  //bulker just gives you the next slice once you "resolve"
  await bulker([0, 1, 2, 3, 4], 2).forEach(async (users, i, done) => {
    await Promise.all(users.map(doSomethingWithUser))
    if (done) return
    return new Promise((ok, ko) => setTimeout(ok, 1000))
  })
  console.log('done!')
})()


推荐阅读