Javascript setInterval:多个间隔

Javascript setInterval: multiple intervals

本文关键字:setInterval Javascript      更新时间:2023-09-26

我在玩动画。我试图让两个圆移动指定的距离,然后停止。我遇到的问题是多个间隔。我将每个间隔分配给一个唯一的变量,并清除该变量,但第一个间隔继续。

这是代码:

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

然后,假设我在 while 循环中给出以下指令:

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

最终发生的事情是,两个玩家都开始向右移动,但玩家 2 在单个 wu 或宽度单位后停止,而玩家 1 继续前进。如果我将指令更改为仅"moveRight(1);",则玩家一移动一个wu并停止。

这是怎么回事?

这只是

一个猜测,因为只有部分代码很难说出发生了什么,但是可能是您分配了两次currnetLoc,因此第一个玩家的位置将始终与p2Loc[0]进行比较?

因此,当您调用moveRight(1)时,它会currentLoc设置为p1Loc[0]然后继续。然后在您调用moveRight(2)后立即将currentLoc设置为 p2Loc[0] .所以现在玩家 1 的间隔比较不再是p1Loc[0]>currentLoc+wu,而是p2Loc[0]>currentLoc+wu。根据p2Loc的值,这可能始终是false

这一行:

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

有点吓人。不要为此使用全局,尤其是当您在函数的第二个条目上重新分配其值时:

currentLoc = p2Loc[0];

那可能是你的问题。

如果您需要跟踪单个玩家的位置,请创建一个玩家对象并在其中跟踪它,如下所示:

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

并将其传递给 moveRight()