Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

144
Visualizações
clear interval not working with if else condition
    <div class="box" style="margin-top:80px;margin-bottom:80px">

            <div class="back">

            <div class="container skills set" id="set">

                <span id="percent">100</span><span>%</span>

            </div>

            </div>

      <div ><span id="damage">2000</span><span>/2000</span></div>

        </div>
<button  onclick="cli()" >click me </button>

Above is the html and below is the js

    var health = parseInt(document.getElementById("damage").innerHTML);

        if(health > 0){

       var myInterval = setInterval(cli, 1000); 

    }

    else {

        clearInterval(myInterval);
console.log("sttoped");
    }

    

function cli(){

    var rand = Math.floor(Math.random() *1000)+1;

    console.log("running");

     var on=document.getElementById("percent");

    var content = document.getElementById("set");

 health = health - rand;

var calc = Math.floor((health/2000)*100);

document.getElementById("damage").innerHTML = Math.floor(health);

if(health < 0){

    document.getElementById("damage").innerHTML = 0;

    content.style.width = 0;

    on.innerHTML = "0";

}

 else{

    on.innerHTML = calc;

        content.style.width = `${calc}%`;

 

}

    }

    

I am trying to run the function per 1 sec only if the health is above 0 and stop the interval if it drops below 0, but it's not working and it's not showing any error on console, any help would be greatly helpful. Here is the codepen link for live preview and test.

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda