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 <
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);
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();