0

Hello i want to have 4 timeOuts to update balls positions because the balls don't go at the same speed. here's a part of my code:

var i=1;
    while(i<=5)
    {
        console.log(i);
        intervals[i-1]=setInterval(function()
        {
            MoveBallHorizontalyWithSpeed(i);
            MoveBallVerticalyWithSpeed(i);
            showBalls();
            console.log(i);
        },speed/i);
        i++;
    }

the problem is that each timeout calls the functions with 6 but i whant the first timeout calling MoveBallHorizontalyWithSpeed(1) the second MoveBallHorizontalyWithSpeed(2) etc...

is there a way to do that faster than writing each timeout?

Brinax
  • 38
  • 6

3 Answers3

0

Please try this:

var i=1;
    while(i<=5)
    {
        console.log(i);
const j = i;
        intervals[i-1]=setInterval(function()
        {
            MoveBallHorizontalyWithSpeed(j);
            MoveBallVerticalyWithSpeed(j);
            showBalls();
            console.log(j);
        },speed/j);
        i++;
    }
Rinkal Rohara
  • 232
  • 1
  • 7
0

The problem is that you are using a global variable inside the loop so all the setInterval functions are using the same variable i, in this type of scenario always use a local variable. You should change your code like this:

for(let i = 1; i<=5; i++)
{
    console.log(i);
    setInterval(function()
    {
        console.log(i);
    },2000);
}
Harsh Saini
  • 598
  • 4
  • 13
0

The reason the while loop will finished its execution and will update the value of the i. So when setInterval execute it get the most latest value of i that is 6.

To avoid this you can create a closure and an IIFE and pass the value of i as a parameter to IIFE. Inside IIFE you can call setInterval

var i = 1;
intervals = [];
while (i <= 5) {
  intervals[i - 1] = (function(x) {
    setInterval(function() {
      MoveBallHorizontalyWithSpeed(x);
      MoveBallVerticalyWithSpeed(x);

    }, 10 / x);

  })(i)
  i++;
}

function MoveBallVerticalyWithSpeed(speed) {
  console.log(speed)
}

function MoveBallHorizontalyWithSpeed(speed) {
  console.log(speed)
}
brk
  • 48,835
  • 10
  • 56
  • 78