消除输入,启动定时器2分钟

时间:2014-12-29 17:17:59

标签: javascript timer

我目前有一个计时器,允许用户选择他们想要计时器的倒计时多长时间。我想要发生的只是让计时器从两分钟开始,并在用户点击开始按钮时开始倒计时。这是我的代码

<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>

继承人http://jsfiddle.net/grahamwalsh/0h9t65bs/

1 个答案:

答案 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();
});
带有开始按钮的

update

加入

 <input type="button" onclick="startTimer()" value="Start">