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)
-
it will be always like this unless your function is asynchronousBeingnin– Beingnin2020年10月09日 07:17:03 +00:00Commented Oct 9, 2020 at 7:17
-
1If you use asynchronous functions, you have to use Promises and chain them togetherPeter Lehnhardt– Peter Lehnhardt2020年10月09日 07:18:04 +00:00Commented 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 waitBeingnin– Beingnin2020年10月09日 07:18:32 +00:00Commented Oct 9, 2020 at 7:18
1 Answer 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
}
}
answered Oct 9, 2020 at 7:21
Beingnin
2,4622 gold badges23 silver badges44 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Random Dude
Didn't work for some reason. Also my heavydutyfn() is async too. Should I remove it?
Beingnin
this is just an example depicting your situation. You should learn to create promises first which essentially uses for i/o operations
Random Dude
Did something like: doFunc();async function rFunc(){//Function here} async function doFunc() {for(i=0; i<20; i++){ await rFunc() } }
lang-js