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>