setInterval太快了 [英] setInterval going too fast

查看:168
本文介绍了setInterval太快了的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JS的新手,并决定开始通过制作小游戏来学习。我正在使用setInterval来自动化敌人的攻击。对于他们的第一次攻击,间隔是正确的,但是在第二次攻击之后,它加速攻击几乎三次或更多,一秒钟。一旦玩家或敌人的生命值达到0,我也无法停止间隔。

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


推荐答案

你再次再次调用'setInterval'。每个调用都是并行运行。

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

如果您有多个warrior对等类型(archer,knight等),请创建一个具有单独设置间隔的数组每个。

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

如果看起来如此,你只有一个并且他们每回合随机玩,添加 clearInterval 在每个 setInterval

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

这篇关于setInterval太快了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆