Javascript计时器无法正常运行

时间:2014-12-29 18:25:00

标签: javascript timer

我目前有一个无效的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/

1 个答案:

答案 0 :(得分:1)

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

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

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