Good evening, I am new to javascript and I would like you to help me, please. I am creating a small practice example where I have a button that every time I click it should show me the numbers from 1 to 100, but for some reason it does not change. my foreach cycle only prints the number 100, why does this happen?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript">
function Incrementar(){
let Nums = 100;
let GuardarValor;
for(var i = 0; i <= Nums; i++){
document.getElementById('Numeros').innerText = i;
}
}
</script>
</head>
<body>
<main>
<h1>COUNTER</h1>
<label id="Numeros"></label>
<br>
<button onclick="Incrementar()">Incrementar</button>
</main>
</body>
</html>
The problem is that the innerText overwrites the content, so the 100 numbers are actually being printed, only it does so very quickly, only the last number being finally printed.
What you could do for example is when you do the
innerText =
replace withinnerText +=
. What this would do is add the new value to the content you already have.a += b for this context gives the same result as a = a + b . In this case a would be innerText and b would be the value to add.
I also added a line break so that one number is below the other.
The code would be something like this:
Just in case, because it was not clear to me in your question, I will leave you what would be a solution (you can run it right here to check its operation) in case you prefer to see the numbers in the same place but more little by little instead of concatenating them:
You will find the explanation in the comments of the function, where you will see that it is a recursive function instead of a loop, in order to better implement the setTimeOut() method that I had already advanced in the comments.