Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Show variable value each time loop runs not just final outcome

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)!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading