0

I have a problem with the following code:

    for (var i = 0; i < balls.length; i++) {
    balls[i].display();
    balls[i].move();
    for (var j = 0; j < balls.length; j++) {
        if (i != j && balls[i].collide(balls[j])) {
            if (balls[i].makeNewBall == true && balls[j].makeNewBall == true) {
                balls.push(new bold());
                balls[i].makeNewBall = false;
                balls[j].makeNewBall = false;
                console.log("if statement works!");
                setTimeout(function() {balls[i].makeNewBall = true; console.log("ball i works");},1000)
                setTimeout(function() {balls[j].makeNewBall = true; console.log("ball j works");},1000)
            }
        }
    }
}

First off, a bit of background:

I have made a code that checks collision between two balls. If two balls collide , it will add a new ball to the array, as well as setting a variable to false. The variable is in place to work as a form of cooldown so that it does not continuously spawn new balls, while they are colliding. The variable is "makeNewBall", and has to be true for a new ball to be made. After a new ball has been made, this variable becomes false. After that, I have made a setTimeout function, that after 1 second, sets this value to true gain.

The problem:

When I use the variables "i" and "j" as array numbers, in the two setTimeout functions, it says "Uncaught TypeError: Cannot set property 'makeNewBall' of undefined". If I instead of "i" and "j" put in numerical values, it works fine, but only for the balls having those numbers obviously

So why can I not use "i" and "j" from the for-loop, in the setTimeout function? Both the functions lie within the same for-loop as some of the other code, but the other code can still use i and j. Shouldn't the setTimeout functions still have access to the same variables, since they are within the same for-loops?. I have read JavaScript closure inside loops – simple practical example, but i still do not understand why mine does not work.

  • But since the two setTimeout functions lie within the two for-loops, shouldn't they both have access to the "i" and the "j" variable? – Main man Sanix Nov 30 '17 at 17:14
  • Yes, they have access to the *variable*, but with the value at execution time (*after* the timeout). So both are beyond the length of the array. To show that, log the values of i and j (instead of setting makeBall to true) – Hans Kesting Dec 01 '17 at 09:20

0 Answers0