如果执行时间超过20秒,如何打破nodejs for循环



假设我有一个执行的forloop。如果执行for循环的时间超过20秒,我想中断它。

async function mainFunc(){
for (let step = 0; step < 5; step++) {
// Runs some complex operation that is computationally intensive
//someFunc() is a async method. SomeAnotherFunc() is a synchronous one.
await someFunc();
someAnotherFunc();//this function contains built in function 
// execSync() that runs command line functions 
await someFunc(); 

}
}

有人能为我提供一个简单的解决方案吗?在这个解决方案中,跟踪时间和中断循环发生在一个单独的线程上,这样我就不会给现有的循环执行带来负担?

这个答案对我部分有效。@Molda给出的解决方案只会在异步方法的情况下对我有所帮助。如果你看到我提供的代码片段,有一个名为someAnotherFunc((的同步方法,它有一个nodejs进程函数"execSync";运行命令行功能。现在,跟踪这个函数的时间实际上是我的一个痛点,因为我无法访问该方法,因为它是一个内置函数。如果你能就如何进一步行动提出建议,我将不胜感激。

这应该是一个相当简单的

var stop = false;
setTimeout(()=>{ stop = true; }, 20 * 1000);
for (let step = 0; step < 5; step++) {
if (stop) break;
}

注意:

没有async/await的for循环是同步的,这意味着即使调用多个请求/db调用等,for循环也只需要不到一秒钟的时间就可以完成。所以我无法想象你会在里面做什么,这需要20秒的

您是否尝试在for循环中添加计时器,以及它何时完成20秒的中断?

如何在Angular 5中进行计时器
https://www.w3schools.com/js/js_break.asp

类似这样的东西:

var stopTimer = false;
setTimeout(() => {
stopTimer = true;
}, 20 * 1000);
for (let step = 0; step < 5; step++) {
if (stopTimer) break;
}

最新更新