Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

140
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!