0

I've been having some trouble with my code. I can't seem to get a while loop to countdown seconds. How many zeros do you have to have at the end of a number to get 1 second?

    var Time = Math.floor((Math.random() * 1500000) + 500000); // trying to make this use seconds not whatever it uses /\   
    console.log(Time / 100000);
     //defining a random variable
    while (Time >= 0) {
      if (Time == 0) {
        document.write("done");
      }
      Time--;
    }
Ashton Cross
  • 3
  • 1
  • 4
  • duplicate of http://stackoverflow.com/questions/20618355/the-simplest-possible-javascript-countdown-timer – Blag Dec 05 '15 at 01:00

2 Answers2

1

It is not a really good idea to use cpu cycles logic inside a loop in order to define seconds for your countdown.

You can use setInterval function as follows:

    var seconds = 10;
    var timer = setInterval(function() {
       seconds--;
        if(seconds == 0) {
            document.write("done");
            clearInterval(timer);
        } else {
            document.write(seconds + " seconds left");
        }
}, 1000);
rpirsc13
  • 443
  • 5
  • 14
0

Here is my implementation

//param 10 is the amount of seconds you want to count down from
countdown(10);

function countdown(x) {
    if(x) {
        console.log(x+ " seconds left...");
        // will call itself until x=0
        setTimeout(countdown, 1000, --x);
    } else {
        // no timer needed to be cleaned up
        console.log("Done...");
    }
}
mjwjon
  • 316
  • 1
  • 4