-1

At the moment I want to convert this code so that it doesn't show the value of i in prompt boxes. I need it to repeatedly update the value of i inside a dedicated <div>. This should occur every second, hence the delay in the loop by 1000ms. How do I convert this code then?

for(var i = 0; i > 10; i++) {
    setInterval(alert(i),1000);
}

I need it to show in here:

<div id="timer"></div>
Terry
  • 63,248
  • 15
  • 96
  • 118
Rumen Hristov
  • 867
  • 2
  • 13
  • 29
  • You can set the `innerHTML` property of the element in an anonymous function executed by the `setInterval()` function. – Terry Oct 18 '16 at 22:02

1 Answers1

7

Do use getElementById() to get the element.

Do use innerHTML to set the text content.

Don't use setInterval in loops (unless you mean to) because that will cause the callback you give to the setInterval to be executed n number of times every timeout.

Do use clearInterval to stop the interval from executing when you are done.

var el = document.getElementById("timer");
var i = 0;

var interval = setInterval(function() {
  el.innerHTML = i++;
  if (i > 10) {
    clearInterval(interval);
  }
}, 1000);
<div id="timer"></div>

Alternatively, use setTimeout and avoid setInterval and clearInterval. Then you can simply not make a new timeout when you are above your maximum count.

var el = document.getElementById("timer");
var i = 0;

function counter() {
  el.innerHTML = i++;
  if (i <= 10) {
    setTimeout(counter, 1000);
  }
}

counter();
<div id="timer"></div>
zero298
  • 25,467
  • 10
  • 75
  • 100