事件侦听器仅设置一次间隔,但每次都设置 运行 其他功能
Setting interval only once by an event listener, but run other functions every time
查看此代码:
function handleTouchStart(event) {
event.preventDefault();
cnvs.removeEventListener("touchstart", handleTouchStart);
var x1 = event.touches[0].clientX-cnvs.offsetLeft;
callerOfCNVSTouchStart = setInterval(function () {
if (x1 > cnvs.width/2 && whiteShip.x2 < cnvs.width) {
whiteShip.x1+= 3;
} else if (x1 < cnvs.width/2 && whiteShip.x1 > 0) {
whiteShip.x1-= 3;
}
}, 20);
nBMC = setInterval(makeNewBullets,200);
setInterval(sendEnemies,2000);//I want to run this line only once
}
我希望其他函数在每次事件发生时都运行,但只为sendEnemies
设置一次间隔。我该怎么做?
在函数handleTouchStart
外部使用像var sentEnemies = false;
这样的变量,并在函数中第一次将其更新为true
,并使用if(!sentEnemies)
让该行只执行一次.
var sentEnemies = false;
function handleTouchStart(event) {
event.preventDefault();
cnvs.removeEventListener("touchstart", handleTouchStart);
var x1 = event.touches[0].clientX-cnvs.offsetLeft;
callerOfCNVSTouchStart = setInterval(function () {
if (x1 > cnvs.width/2 && whiteShip.x2 < cnvs.width) {
whiteShip.x1+= 3;
} else if (x1 < cnvs.width/2 && whiteShip.x1 > 0) {
whiteShip.x1-= 3;
}
}, 20);
nBMC = setInterval(makeNewBullets,200);
if (!sentEnemies) {
setInterval(sendEnemies,2000); // Will execute only once
sentEnemies = true;
}
}
查看此代码:
function handleTouchStart(event) {
event.preventDefault();
cnvs.removeEventListener("touchstart", handleTouchStart);
var x1 = event.touches[0].clientX-cnvs.offsetLeft;
callerOfCNVSTouchStart = setInterval(function () {
if (x1 > cnvs.width/2 && whiteShip.x2 < cnvs.width) {
whiteShip.x1+= 3;
} else if (x1 < cnvs.width/2 && whiteShip.x1 > 0) {
whiteShip.x1-= 3;
}
}, 20);
nBMC = setInterval(makeNewBullets,200);
setInterval(sendEnemies,2000);//I want to run this line only once
}
我希望其他函数在每次事件发生时都运行,但只为sendEnemies
设置一次间隔。我该怎么做?
在函数handleTouchStart
外部使用像var sentEnemies = false;
这样的变量,并在函数中第一次将其更新为true
,并使用if(!sentEnemies)
让该行只执行一次.
var sentEnemies = false;
function handleTouchStart(event) {
event.preventDefault();
cnvs.removeEventListener("touchstart", handleTouchStart);
var x1 = event.touches[0].clientX-cnvs.offsetLeft;
callerOfCNVSTouchStart = setInterval(function () {
if (x1 > cnvs.width/2 && whiteShip.x2 < cnvs.width) {
whiteShip.x1+= 3;
} else if (x1 < cnvs.width/2 && whiteShip.x1 > 0) {
whiteShip.x1-= 3;
}
}, 20);
nBMC = setInterval(makeNewBullets,200);
if (!sentEnemies) {
setInterval(sendEnemies,2000); // Will execute only once
sentEnemies = true;
}
}