I’m trying to display a countdown from 10 in my HTML.
This comes from a for loop which decrements down from 10.
The problem I have is since the loop counts down and stops at 0 the value I’m displaying is the final value rather than printing all the values (if that makes sense)!
How can I display all of them in my HTML?
Code:
let countdown = 'Countdown 10';
for (let i = 10; i >= 0; i--) {
if (i === 10) {
countdown = 'Countdown 10';
} else if (i === 0) {
countdown = 'Blast off!';
} else {
countdown = i;
}
console.log(countdown);
};
let output = document.querySelector('.output');
output.innerHTML = '';
const para = document.createElement('p');
para.textContent = countdown;
output.appendChild(para);
I’m sure I can do something with the para.textContent e.g. putting it into the loop. But I’m not sure how.
>Solution :
you should assign the value to the HTML element and append that element to document inside the loop block with a delay
let delay = 300;
let count = 10;
const output = document.querySelector('.output');
const para = document.createElement('p');
output.appendChild(para);
for (let i = count; i >= 0; i--) {
let countdown = i;
if (i === 10) {
countdown = 'Countdown 10';
} else if (i === 0) {
countdown = 'Blast off!';
}
setTimeout(()=>{
para.textContent = countdown;
}, (count - i) * delay)
};
<div class="output"></div>