Home > Net >  Show variable value each time loop runs not just final outcome
Show variable value each time loop runs not just final outcome

Time:12-02

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.

CodePudding user response:

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You just need to set up your elements first, so you can write to them along the way. Using a for loop will cycle through so fast, you won't see the countdown happen, so I also show an alternate version using setInterval, which allows you to control the time in between each count.

let countdown = 'Countdown 10';

let output = document.querySelector('.output');
output.innerHTML = '';

const para = document.createElement('p');
output.appendChild(para);


const para2 = document.createElement('p');
output.appendChild(para2);

for (let i = 10; i >= 0; i--) {
  if (i === 10) {
    countdown = 'Countdown 10';
  } else if (i === 0) {
    countdown = 'Blast off!';
  } else {
    countdown = i;
  }
  para.textContent = countdown;
  //console.log(countdown);
};

para2.textContent = 'Countdown 10'
let i = 9,
  intv = setInterval(() => {
    if (i < 0) return clearInterval(intv);
    let countdown = i === 0 ? 'Blast off!' : i
    para2.textContent = countdown;
    i--
  }, 1000)
<div class='output'>
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related