Reputation: 79
I want to count down a counter. However, it always starts one number later. I know the problem, but I can't find the solution.
function countStart() {
const countdown = setInterval(() => {
time -= 1;
document.getElementById('counter').textContent = time;
if (time < 1) {
clearInterval(countdown);
}
}, 1000);
}
If I count down from 10. If it starts at 9, how do I change that?
Upvotes: 1
Views: 42
Reputation: 6904
you just put time-=1
below the line where you change DOM
function countStart(time) {
const countdown = setInterval(() => {
//document.getElementById('counter').textContent = time;
console.log(time)
time -= 1;
if (time < 1) {
clearInterval(countdown);
}
}, 1000);
}
just changed dom manipulation to console.log
Upvotes: 0
Reputation:
You are decreasing your "time" variable before you display it. So if your "time" variable has a value of 10 initially, it will get reduced to 9 before being displayed due to the statement "time -=1" occuring before setting it as textContent for your element (and thus displaying it).
Try decreasing your "time" variable after setting it as textContent of your counter element.
function countStart() {
const countdown = setInterval(() => {
document.getElementById('counter').textContent = time;
time -= 1;
if (time < 1) {
clearInterval(countdown);
}
}, 1000);
}
Upvotes: 1