0

this code just spits out '11' onto the webpage (I don't know how it ever gets to 11, I would think i would be a value of 10:

<!DOCTYPE html>
<html>
<body>
<p id="demo01"></p>

<script>
for(i = 1; i < 10; i++){
    setInterval(function() {
        document.getElementById("demo01").innerHTML = i;
    }, 1000);
}

</script>
</body>
</html>

Anyway, my question is why I can't see the counting occur every second?? Shouldn't I see it go from 1-10?

Because if I change the code to this:

<!DOCTYPE html>
<html>
<body>
<p id="demo01"></p>

<script>
for(i = 1; i <= 10; i++){
    setInterval(function() {
        document.getElementById("demo01").innerHTML = Math.floor(1000*Math.random());
    }, 1000);
}

</script>
</body>
</html>

I do see a random number every 1 second, but it doesn't stop after 10 loops! It just keeps going forever.

Can someone point me in the right direction for what is going on here?

Thanks.

phindex
  • 51
  • 2
  • https://stackoverflow.com/questions/111102/how-do-javascript-closures-work – Will Sep 05 '17 at 04:37
  • There is also another problem here in that you are using setInterval. Try setTimeout instead (as explained here https://www.w3schools.com/jsref/met_win_setinterval.asp: to execute a function only once, after a specified number of milliseconds, use the setTimeout() method.) – nzjoel Sep 05 '17 at 04:38
  • I *am* trying to make the code repeat 10 times though... so I can watch a counter go from 1 to 10. Is there a better way to do that? – phindex Sep 05 '17 at 11:20

0 Answers0