-1

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

2 回答 2

0

计时器只触发一次。确保将以下行放在 countDown 函数的末尾,以便再次调用它:

timer = setTimeout(countDown, 1000); 
于 2013-10-28T20:51:19.790 回答
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"); 
   }
}
于 2013-10-28T20:49:30.363 回答