Fix timer starting on page load
A simple Javascript timer tha开发者_开发技巧t runs for 30 seconds and displays a message once it reaches 0. I cant figure out how to get it to start when a button is pressed instead of on pageload. Any help is appreciated :)
<script type="text/javascript">
var sec = 30; // set the seconds
var min = 00; // set the minutes
function countDown() {
sec--;
if (sec == -01) {
sec = 59;
min = min - 1;
} else {
min = min;
}
if (sec<=9) { sec = "0" + sec; }
time = (min<=9 ? "0" + min : min) + " min and " + sec + " sec ";
if (document.getElementById) { theTime.innerHTML = time; }
SD=window.setTimeout("countDown();", 1000);
if (min == '00' && sec == '00') { sec = "00"; window.clearTimeout(SD); alert("Too slow."); }
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(function() {
countDown();
});
</script>
<button onclick='countDown();'>Click Me</button>
And just don't call addLoadEvent() at all.
Add event listener to the button in the load function and then call countDown
addLoadEvent(function() {
var el = document.getElementById("startButton");
el.addEventListener("click", countDown, false);
});
Here the full example link
Here's a full sample with start/stop and remaining time display.
var gTimer = null
function endOfTimer() {
console.log("here");
window.alert('Too slow');
}
function start() {
gTimer = window.setTimeout('endOfTimer', 1 * 1000);
}
精彩评论