Reputation: 25
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 is executed completely for loop shouldn't move forward.. How to do that? I tried simulating goto but it didn't work..
Here's my code:
function startLoop(i) {
console.log("startloop function start");
var centerX = xObj[i];
var centerY = yObj[i];
var radius = 10;
var alpha = 1, /// current alpha value
delta = 0.01; /// delta = speed
var flag = 0;
var num = 0
function loop() {
console.log("inside loop " + centerX + " " + centerY);
alpha -= delta;
if (alpha <= 0) {
//console.log("heya_amigoes");
num = 2;
return;
}
//console.log("hi1");
/// clear canvas, set alpha and re-draw image
ctx2.clearRect(0, 0, 1000, 600);
ctx2.globalAlpha = alpha;
ctx2.beginPath();
ctx2.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
ctx2.fillStyle = "#FF0000";
ctx2.fill();
ctx2.lineWidth = 1;
ctx2.strokeStyle = '#003300';
ctx2.stroke();
//console.log("hi2");
//requestAnimationFrame(loop); // or use setTimeout(loop, 16) in older browsers
setTimeout(loop, 16)
console.log("Outside function loop");
}
loop();
/*
LABEL1: do {
if(num==2)
{
num=0;
break LABEL1;
}
if(num!=2)
continue LABEL1;
}while(1);
*/
console.log("startloop function stop");
}
for (i = 0; i < xObj.length; i++) {
console.log("for loop running " + i);
startLoop(i);
console.log("outside loop func");
}
Upvotes: 0
Views: 92
Reputation: 24915
A for loop will not wait for your task. To achieve this task, you will have to use recursion
.
Logic:
var count = 0
function test1(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:
count = 0
{...}
. In my case: test1(count, test1)
if(i<10)
. If condition is satisfied, start next iteration: setTimeout(cb.bind(null, ++count, cb), 2000)
++count
This is the final JSFiddle
Upvotes: 1
Reputation: 8340
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");
}
Upvotes: 0