ZAR
ZAR

Reputation: 2736

Javascript setInterval: multiple intervals

I'm playing with animations. I'm trying to have two circles move a specified distance and then stop. The issue I'm having is with multiple intervals. I assign each interval to a unique variable, and clearInterval that variable, but the first interval continues on.

Here is the code:

function moveRight(player){

if(player==1){
    currentLoc = p1Loc[0];            //global var with player's current location
    intervalR1 = setInterval(function(){
        p1Loc[0]+=1;
        draw();                      //function that redraws the canvas
        if(p1Loc[0]>currentLoc+wu){  //wu is a single "width-unit"
            clearInterval(intervalR1);
        }
    },5)
}
else{
    currentLoc = p2Loc[0];
    intervalR2 = setInterval(function(){
        p2Loc[0]+=1;
        draw();
        if(p2Loc[0]>currentLoc+wu){
            clearInterval(intervalR2);
        }
    },5)
}

}

Then, let's say I give the following instructions within a while loop:

instructions = ["moveRight(1)", "moveRight(2)"];
for(instruction in instructions){
    eval(instructions[instruction]); //I know, eval(), ugh. Is just temporary
}

What ends up happening is, both players start moving right, but player 2 stops after a single wu, or width-unit while player one keeps going. If i change the instructions to only "moveRight(1);", then player one moves a single wu and stops.

What's going on here?

Upvotes: 0

Views: 313

Answers (2)

Michael B.
Michael B.

Reputation: 351

This line:

currentLoc = p1Loc[0];            //global var with player's current location

is kinda scary. Don't use a global for this, especially when you re-assign its value on the second entry to the function:

currentLoc = p2Loc[0];

That's likely your problem.

If you need to keep track of a single player's position, create a player object and keep track of it in there, something like:

function Player(number) {
    this.number = number
    this.position = 0 //some default initial position
}

and pass this into moveRight()

Upvotes: 1

isomarcte
isomarcte

Reputation: 1981

This is just a guess, since is a bit hard to tell what is going on with only part of the code, but could it be that you are assigning currnetLoc twice, and thus the first player's location will always be always be compared against p2Loc[0]?

So when you call moveRight(1) it sets currentLoc to p1Loc[0] then proceeds. Then immediately after you call moveRight(2) which sets currentLoc to p2Loc[0]. So now the comparison for the interval for player 1 is no longer p1Loc[0]>currentLoc+wu, but rather p2Loc[0]>currentLoc+wu. Depending on the value of p2Loc this may always be false.

Upvotes: 1

Related Questions