1

我有一个如下所示的循环。

let currentResult = []
for(let i = 0; i < maxIterations; i++) {
    currentResult = someComputation(...)
    if(endingCondition) {
       break
    }
}
return currentResult

我不仅想要迭代限制,还想要时间限制。

我知道我可以用它Date.now()来获取开始时间,然后检查每次迭代后经过了多长时间。

但是,它会在完成当前迭代后停止,这意味着它会稍微超出时间限制。

我想要的是settimeout,当时间结束时,它只是返回currentResult并放弃正在进行的迭代。

4

1 回答 1

2

通过利用生成器函数,您可以实现可以在中间停止的函数:

  function limited(time, fn) {
   return function(...args) {
     const it = fn(...args), start = Date.now();
     while(Date.now() - start < time) {
       const { value, done } = it.next();
       if(done) return { value };
     }
     return { terminated: true };
   }
 }

 const longComputation = limited(1000, function* () {
   while(true) {
     yield; // < breaking point for safe termination
   }
 });

for(let i = 0; i < maxIterations; i++) {
  const { result, terminated } = longComputation(...);
  if(terminated) {
     break
  }
}
于 2020-02-06T10:10:10.407 回答