简体   繁体   中英

Javascript Timer Not Functioning Correctly

I currently have a javascript timer that is not working correctly. A Two minute timer should start once the start timer button is clicked. here is my code

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.");       }
 }); 

}
}

here is a fiddle http://jsfiddle.net/grahamwalsh/8mmqxsto/

When you define inline event handlers on your html you must be sure that your js was loaded early (just before the dom loads):

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

In your fiddle, configure it to be loaded in <head>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM