Search code examples
javascripthtmlloopstimeoutupdates

javascript setTimeout in a while loop


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?


Solution

  • 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);
    }