Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to break a nodejs for loop if the execution takes more than 20 seconds?

Suppose I have a forloop that does some execution. I would like to break the for loop if it takes more than 20 seconds to execute.


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();
await someFunc(); 
 
}
}

Can anyone provide me a simple solution where tracking the time and breaking the loop happens on a separate thread so that I don’t burden my existing for loop execution?

Please note:I have removed the dummy code and I have given explanation in the comments. I belive that I found the solution given below by one of the users and it seems perfect.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

That should be fairly simple

var stop = false;
setTimeout(()=>{ stop = true; }, 20 * 1000);

for (let step = 0; step < 5; step++) {
    if (stop) break;
}

Note:

The for loop without async/await is synchronous which means even calling multiple requests/db calls/ etc. will only take less then a second for the for loop to finish. So i can’t imagine what you would do in it that would take 20 seconds

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading