我目前有一个计时器,允许用户选择他们想要计时器的倒计时多长时间。我想要发生的只是让计时器从两分钟开始,并在用户点击开始按钮时开始倒计时。这是我的代码
<body>
<div id="countdown"></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 {
function display( notifier, str ) {
document.getElementById(notifier).innerHTML = str;
}
function toMinuteAndSecond( x ) {
return Math.floor(x/60) + ":" + x%60;
}
function setTimer( remain, actions ) {
(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 () { alert( "Time is up. Please Sumbit Vote."); }
});
}
}
}
</script>
Set Time Limit: <input type="text" id="userTime" />
<input type="button" value="Start" onclick="startTimer()" />
</body>
答案 0 :(得分:0)
尝试this小提琴
function startTimer() {
userInput = 120;
if(userInput.length == 0){
alert("Please enter a value");
} else {
var numericExpression = /^[0-9]+$/;
function display( notifier, str ) {
document.getElementById(notifier).innerHTML = str;
}
function toMinuteAndSecond( x ) {
return Math.floor(x/60) + ":" + x%60;
}
function setTimer( remain, actions ) {
(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 () { alert( "Time is up. Please Sumbit Vote."); }
});
}
}
document.addEventListener("DOMContentLoaded", function(event) {
startTimer();
});
带有开始按钮的
加入
<input type="button" onclick="startTimer()" value="Start">