Rumen Hristov Rumen Hristov - 1 month ago 6
HTML Question

How to repeatedly update the contents of a <div> by only using JavaScript?

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>

Answer

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>