Keep For Loop From Executing In Javascript
Currently for loop gets executed till the end even though the function it calls hasn't finished executing. I want to make it such that, when startloop function is called until it i
Solution 1:
A for loop will not wait for your task. To achieve this task, you will have to use recursion
.
Logic:
- Call a function and pass a callback in it.
- On execution completion, run passed callback.
- Now since we have to chain same function again and again, pass same callback to next iteration again and have a check(threshold limit) and stop on breach.
var count = 0functiontest1(i, cb){
console.log("In Test " + i)
if(i < 10)
setTimeout(cb.bind(null, ++count, cb), 2000)
}
test1(count, test1)
Explanation:
My approach mimics behaviour of a do..while
loop. It has 4 parts:
- Initialisation: This will initialise the iterator variable. This variable will be use to check for termination condition and to check the current iterator's value. In my Case:
count = 0
- Execution of Code block: This will execute the code defined inside
{...}
. In my case:test1(count, test1)
- Termination condition: This check if next iteration should be performed or not? In my case:
if(i<10)
. If condition is satisfied, start next iteration:setTimeout(cb.bind(null, ++count, cb), 2000)
- Increment Value: This updated value of iterator to point to next value. In my case:
++count
This is the final JSFiddle
Solution 2:
I think that the problem going to be with your for
loop. startLoop
function always going to get the xObj.length-1
.
You can read more about this problem: JavaScript closure inside loops – simple practical example
The variable
i
, within each of your anonymous functions, is bound to the same variable outside of the function.
Solution with ES6 let
feature:
for (let i = 0; i < xObj.length; i++) {
console.log("for loop running " + i);
startLoop(i);
console.log("outside loop func");
}
Solution without ES6:
var funcs = [];
for (var i = 0; i < xObj.length; i++) {
funcs[i] = startLoop(i);
}
for (var i = 0; i < xObj.length; i++) {
console.log("for loop running " + i);
funcs[i]();
console.log("outside loop func");
}
Post a Comment for "Keep For Loop From Executing In Javascript"