修复计时器从页面加载开始

时间:2011-09-04 08:01:45

标签: javascript forms timer pageload

一个简单的Javascript计时器,运行30秒并在达到0时显示一条消息。我无法弄清楚如何在按下按钮而不是在页面加载时启动它。任何帮助表示赞赏:)

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

3 个答案:

答案 0 :(得分:1)

<button onclick='countDown();'>Click Me</button>

根本就不要调用addLoadEvent()。

答案 1 :(得分:0)

将事件侦听器添加到加载函数中的按钮,然后调用countDown

 addLoadEvent(function() {
   var el = document.getElementById("startButton");   
     el.addEventListener("click", countDown, false); 
});

这里是完整示例link

答案 2 :(得分:0)

这是full sample,其中包含开始/停止和剩余时间显示。

var gTimer = null

function endOfTimer() {
    console.log("here");
    window.alert('Too slow');
}

function start() {
    gTimer = window.setTimeout('endOfTimer', 1 * 1000);
}