I'm sorry if I'm being stupid. I am just starting to learn Javascript and am messing around with loops. I'm currently messing about with this code:
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">---</button>
<p id="hpcount"></p>
<p id="demo2"></p>
<script>
var health = 30;
document.getElementById("hpcount").innerHTML = health;
while (health < 0){
health = 0;
document.getElementById("demo2").innerHTML = "Game over";
break;
}
function myFunction() {
if (health>0){
health -= Math.floor(Math.random() * 10)+1;
document.getElementById("hpcount").innerHTML = health;
}
}
</script>
</body>
</html>
The idea is that the button subtracts a random integer 1-10 from the variable "health" as long as health is larger than 0. Then if it goes lower than that, display the "game over" message and reset health to 0. However, while the button stops working once health>0, the message just wont appear, and I just can't figure out why no matter how many times I look over the syntax and structure... Am I being stupid and missing something obvious?
while
is executed when the condition can be evaluated totrue
. In your case the loop is never executed. – Teemu 19 hours ago