0

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");
}
jeff lockhart
  • 25
  • 2
  • 9

2 Answers2

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 = 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:

  1. 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
  2. Execution of Code block: This will execute the code defined inside {...}. In my case: test1(count, test1)
  3. 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)
  4. Increment Value: This updated value of iterator to point to next value. In my case: ++count

This is the final JSFiddle

Rajesh
  • 24,354
  • 5
  • 48
  • 79
  • Hey can you plz explain how your code snippet is working plz? what does the initLoop do? and how can i use this in my code? – jeff lockhart Apr 22 '17 at 04:27
  • ok I am trying to do that.. and the function test1 gets replaced by my second function loop? – jeff lockhart Apr 22 '17 at 04:34
  • https://jsfiddle.net/1o3e8sbs/ Hey check this fiddle out. I tried using your code with a for loop just to check if it works but it is giving unexpected results.. – jeff lockhart Apr 22 '17 at 04:44
  • Also i think, instead of using for loop, i can set the length to a variable say `x` and using your code i can check that, `if(i – jeff lockhart Apr 22 '17 at 05:08
  • Please check the update. Have added explanation and made code snippet little more simple. – Rajesh Apr 22 '17 at 05:32
0

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");

}
Community
  • 1
  • 1
Peter Kota
  • 8,048
  • 5
  • 25
  • 51
  • no this is not the case as i am passing the value of i and getting the values inside the function.. problem is it's not one after one. it keeps getting executed one by one with decreasing alpha value – jeff lockhart Apr 21 '17 at 06:25