Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

141
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda