Я новичок в Javascript и немного поиграл с таймерами. Я нашел код для таймера обратного отсчета на основе ввода тестового поля here, и я попытался добавить таймер подсчета на ту же страницу, но он не работает.Счетчик обратного отсчета и таймера Javascript на основе ввода пользователем
<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>
В принципе, я попытался создать новую переменную (countuptime), который начинается с 0 и идет вверх, пока он не будет таким же, как UserInput, в какой момент он должен остановиться. Однако, когда я пытаюсь проверить, таймер подсчета отображает NaN: NaN. Я пытаюсь держаться подальше от JQuery прямо сейчас и получить основы Javascript.
ах, глупо меня. Спасибо! – an14