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");
}
3
  • Please click the <> and the rest of the html to show a minimal reproducible example - it is currently not clear at all what your expected and actual output is Commented Apr 21, 2017 at 5:49
  • You will have to use recursion and function callbacks for it Commented Apr 21, 2017 at 5:51
  • 1
    @SarathSadasivanPillai - making a snippet means making working code! Commented Apr 21, 2017 at 5:57

2 Answers 2

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

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

5 Comments

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?
ok I am trying to do that.. and the function test1 gets replaced by my second function loop?
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..
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<x) maybe? and pass the value of next i to get the desired co-ordinates?
Please check the update. Have added explanation and made code snippet little more simple.
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");

}

1 Comment

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

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.