如何创建倒数计时器,用户输入任何数字并将其从该数字显示为零?

时间:2013-10-28 20:42:45

标签: javascript timer

如何创建倒数计时器,用户以秒为单位输入时间并在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"); 
   }
}

2 个答案:

答案 0 :(得分:0)

你的错误是:counter永远不会被定义。将其替换为userChoice,它完全按照您的方式运行:

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"); 
   }
}

答案 1 :(得分:0)

计时器仅触发一次。请务必将以下行放在countDown函数的末尾,以便再次调用它:

timer = setTimeout(countDown, 1000);