我是Javascript的新手,并且正在和计时器玩游戏。我根据测试字段输入here找到了倒数计时器的代码,我尝试将同步计时器添加到同一页面,但它不起作用。
<html>
<body>
<div id="countdown"></div>
<div id="countup"></div>
<div id="notifier"></div>
<script type="text/javascript">
function startTimer() {
userInput = document.getElementById('userTime').value;
if(userInput.length == 0){
alert("Please enter a value");
} else {
var numericExpression = /^[0-9]+$/;
if(!userInput.match(numericExpression)){
alert("Please enter a number")
} else {
var countuptime = 0;
function display( notifier, str ) {
document.getElementById(notifier).innerHTML = str;
}
function toMinuteAndSecond( x ) {
return Math.floor(x/60) + ":" + x%60;
}
function setTimer( remain, actions, countuptime ) {
(function countup() {
display("countup", toMinuteAndSecond(userInput - countuptime));
(countuptime+= 1) <= userInput && setTimeout(arguments.callee, 1000);
})();
(function countdown() {
display("countdown", toMinuteAndSecond(remain));
actions[remain] && actions[remain]();
(remain -= 1) >= 0 && setTimeout(arguments.callee, 1000);
})();
}
setTimer(userInput, {
10: function () { display("notifier", "Just 10 seconds to go"); },
5: function () { display("notifier", "5 seconds left"); },
0: function () { display("notifier", "Time is up"); }
});
}
}
}
</script>
Please Enter A Number: <input type="text" id="userTime" />
<input type="button" value="Go" onclick="startTimer()" />
</body>
</html>
基本上,我尝试创建一个从0开始的新变量(countuptime),直到它与userInput相同,此时它应该停止。但是,当我尝试测试时,计数器计时器显示NaN:NaN。我现在正试图远离JQuery并获得Javascript的基础知识。
答案 0 :(得分:0)
当你定义&#34; setTimer&#34;你设置3个参数的功能,但是当你调用它时,你提供了两个参数。这就是为什么第三个参数&#39; countuptime&#39;仍未定义。您也不必从userInput中删除countuptime值。看看这个: -
<html>
<body>
<div id="countup"></div>
<div id="notifier"></div>
<script type="text/javascript">
function startTimer() {
userInput = document.getElementById('userTime').value;
if(userInput.length == 0){
alert("Please enter a value");
} else {
var numericExpression = /^[0-9]+$/;
if(!userInput.match(numericExpression)){
alert("Please enter a number")
} else {
var countuptime = 0;
function display( notifier, str ) {
document.getElementById(notifier).innerHTML = str;
}
function toMinuteAndSecond( x ) {
return Math.floor(x/60) + ":" + x%60;
}
function setTimer( remain, actions, countuptime ) {
(function countup() {
display("countup", toMinuteAndSecond(countuptime));
(countuptime+= 1) <= userInput && setTimeout(arguments.callee, 1000);
})();
}
setTimer(userInput, {
10: function () { display("notifier", "Just 10 seconds to go"); },
5: function () { display("notifier", "5 seconds left"); },
0: function () { display("notifier", "Time is up"); }
}, countuptime);
}
}
}
</script>
Please Enter A Number: <input type="text" id="userTime" />
<input type="button" value="Go" onclick="startTimer()" />
</body>
</html>