<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.