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()
相关文章:
- node.js:setInterval()正在跳过调用
- setInterval和clearInterval javascript无法按需工作
- Don'我不明白为什么我的setInterval+jQuery;不起作用
- setInterval游戏循环的范围问题
- JavaScript setInterval problems
- 如何在Javascript中延迟setInterval
- 如何执行相同的setInterval()
- SetInterval在javascript对象中表现怪异
- 从setInterval方法移动到带有sprite的requestAnimationFrame
- 如何在悬停时暂停setInterval
- 可以't获取setInterval函数以使用javascript中的this.function_name调用另一
- 删除对象时终止setInterval
- 使用setInterval()函数进行图像闪烁
- “;对于“;内部”;setInterval”;
- 在setInterval函数之前声明时未定义对象
- 使setInterval和setTimeout工作时出现问题
- 事件循环的MEAN.JS setInterval进程(从另一个服务器获取数据)
- 使用setInterval调用原型函数时出现问题
- setInterval函数不会更改视图中的$scope
- “单独列搜索”上的Datatables setinterval函数