2

I am trying to loop a function but I need the loop to pause, execute the function, then continue the loop. The function takes around 1 to 5 minutes to finish. Then I want to unpause the loop and redo the function 20 times.

What I've tried so far:

for(i = 0; i < 20; i++) {
    //Some function here
}
do {
var i = 0
// Some function here
i++
} while (i < 20)
3
  • it will be always like this unless your function is asynchronous Commented Oct 9, 2020 at 7:17
  • 1
    If you use asynchronous functions, you have to use Promises and chain them together Commented Oct 9, 2020 at 7:18
  • It depends on the type of function you use inside the loop. If it is synchronous, the loop wont iterate till it completes. If its asynchronous you need to await for it to wait Commented Oct 9, 2020 at 7:18

1 Answer 1

1

If your function is asynchronous you could define the loop something like this to wait for the process to complete. For synchronous functions you dont have to do anything. The loop will automatically waits till it completes

async function doAll()
{
  for(i = 0; i < 20; i++) {
    await heavyDutyFn()//this function should return a promise always
  }

}
Sign up to request clarification or add additional context in comments.

3 Comments

Didn't work for some reason. Also my heavydutyfn() is async too. Should I remove it?
this is just an example depicting your situation. You should learn to create promises first which essentially uses for i/o operations
Did something like: doFunc();async function rFunc(){//Function here} async function doFunc() {for(i=0; i<20; i++){ await rFunc() } }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.