Javascript 计时器无法正常工作

Javascript Timer Not Functioning Correctly

本文关键字:工作 常工作 计时器 Javascript      更新时间:2023-09-26

我目前有一个无法正常工作的javascript计时器。单击启动计时器按钮后,应启动两分钟计时器。这是我的代码

.HTML

 <div id="countdown"></div>
 <div id="notifier"></div>
 <input type="button" onclick="startTimer()" value="Start Timer"> 

.JS

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, {
60: function () { display("notifier", "1 Minute Remaining"); },
30: function () { display("notifier", "30 Seconds Remaining");        },
 1: function () { display("notifier", "   ");        },
 0: function () { alert( "Time Is Up. Please Sumbit Vote.");       }
 }); 
}
}

这是一个小提琴 http://jsfiddle.net/grahamwalsh/8mmqxsto/

当你在 html 上定义内联事件处理程序时,你必须确保你的 js 是提前加载的(就在 dom 加载之前):

<html>
    <head>
        <script src="yourScript.js"></script>
    </head>
    <body>
        <input type="button" onclick="startTimer()" value="Start Timer"> 
    </body>
</html>

在您的小提琴中,将其配置为加载<head>