setInterval going too fast

2019-02-27 14:45发布

问题:

I'm new to JS, and decided to start of learning by a making a small game. I am using a setInterval to automate the enemy's attack. For their first attack the interval is correct, but after the second attack it speeds up to attacking almost three times, or more, a second. I'm also having trouble stopping the interval once either the player's or the enemy's health reaches 0.

here is pretty much all the code pertaining my problem. The whole code can be found here

function deadFunct(){
if(yourHealth <= 0){
    window.alert("You dead");
    clearInterval(fightAuto);
    clearInterval(deadAuto);
}
if(enemyHealth <= 0){
    window.alert("The enemy is dead");
    clearInterval(fightAuto);
    clearInterval(deadAuto);
}
}

function nextFunct(){
document.getElementById("nextBtn").disabled=true;
document.getElementById("swordBtn").disabled=false;
document.getElementById("bowBtn").disabled=false;
document.getElementById("hamBtn").disabled=false;
var a=Math.random();
if(a>0.66){
    enemy="Knight";
    eAcc=.75;
    eDmg=5;
    eAttackSpeed=2000;
    y= "Your health = " + yourHealth + " || "+ enemy +" = " + enemyHealth + "<br>";
    document.getElementById("attack").innerHTML=y;
}else if(a>0.33){
    enemy="Archer";
    eAcc=.80;
    eDmg=3;
    eAttackSpeed=1750;
    y= "Your health = " + yourHealth + " || "+ enemy +" = " + enemyHealth + "<br>";
    document.getElementById("attack").innerHTML=y;
}else{
    enemy="Berserker";
    eAcc=.66;
    eDmg=7;
    eAttackSpeed=2500;
    y= "Your health = " + yourHealth + " || "+ enemy +" = " + enemyHealth + "<br>";
    document.getElementById("attack").innerHTML=y;
}
}

function enemyAttackFunct(){
for(var i=0; i<1;i++){
if(enemy == "Archer"){
    fightAuto = setInterval(function(){aAttackFunct()},eAttackSpeed);
    document.getElementById("test").innerHTML=eAttackSpeed;
}else if(enemy == "Knight"){
    fightAuto = setInterval(function(){kAttackFunct()},eAttackSpeed);
    document.getElementById("test").innerHTML=eAttackSpeed;
}else{
    fightAuto = setInterval(function(){bAttackFunct()},eAttackSpeed);
    document.getElementById("test").innerHTML=eAttackSpeed;
}
}
}

回答1:

You keep calling 'setInterval' again again. Each call is running in parallel.

If you have more than one warrior peer type (archer, knight, etc), create an array that will have a separate set interval for each.

If, as seems the case, you only have one and they play at random each turn, add clearInterval before every setInterval



回答2:

you should never use setInterval for animations!

Just use requestAnimationFrame instead!

  • https://developer.mozilla.org/en/docs/Web/API/window.requestAnimationFrame
  • http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
  • http://css-tricks.com/using-requestanimationframe/