How do I create a countdown where the user enters any number and displays that number at zero?

advertisements

How can I create a countdown timer where the user inputs a time in seconds and display it from that number to zero in javascript?

var userChoice = parseInt(prompt("Type in time to countdown"));
var timer = setInterval(countDown, 1000); 

// this is what i have
function countDown() {
   console.log(counter);
   counter--;
   if (counter < 0) {
      clearInterval(timer);
      console.log("END");
   }
}


Your mistake was: counter is never defined. Replace it with userChoice and it works perfectly the way you did it:

var userChoice = parseInt(prompt("Type in time to countdown"));
var timer = setInterval(countDown, 1000); 

function countDown() {
   console.log(userChoice);
   userChoice--;
   if (userChoice < 0) {
      clearInterval(timer);
      console.log("END");
   }
}