-3

I need to make a countdown happen from 10 to 0 using a loop. The loop should replace the need to repeat the code 10X. I also neeed to display the countdown to the user in the HTML. Help!

<script>
       
function StartTheCountdown()
{ 
     var Countdown = 10;
     // Used to keep track of actual time.
     // 1000 = 1 second because we are using milliseconds.
    var timeout = 10000;
    setTimeout(() => {
    document.getElementById("CountDownDisplay").innerHTML = "Blastoff!";
    Countdown = Countdown - 1;
    }, timeout)
    timeout = timeout - 1000;
    // We need to do this 10 times **************************************
    setTimeout(() => {
    document.getElementById("CountDownDisplay").innerHTML = Countdown;
    Countdown = Countdown - 1;
    }, timeout)
    timeout = timeout - 1000; 
}
    </script>
MeganM
  • 11

1 Answers1

0

Use setTimeout to repeatedly call the function until count is zero, and then display a message.

// Cache your element
const div = document.querySelector('div');

// Initialise your count to 10
function countdown(count = 10) {

  // Update your element textContent
  div.textContent = `T-minus: ${count}`;

  // Call the function again if the count
  // is greater than 0 with a decremented count
  if (count > 0) {
    setTimeout(countdown, 1000, --count);

  // Otherwise update the textContent of the
  // element with a message
  } else {
    div.textContent = 'Blast off!';
  }
}

countdown();
<div></div>

Additional documentation

Andy
  • 61,948
  • 13
  • 68
  • 95