JS时钟问题,开始onclick

时间:2017-06-03 11:17:59

标签: javascript jquery html5

所以我正在建立一个游戏,我需要一个计数器。计数器需要启动onclick,当完成时只停止00(从1m到00)。(现在它开始onload,当它达到00时再次启动)。

HTML:

<body>
<div>
 <div class="timer" >Battle time: <span id="time"></span></div>
<p>BATTLE</p>
<BUTTON class="begin" onclick="" ><b>START</b></BUTTON>
</div>
</body>

JS:

function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    setInterval(function () {
        minutes = parseInt(timer / 60, 10);
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.textContent = minutes + ":" + seconds;

        if (--timer < 0) {
            timer = duration;
        }
    }, 1000);
}

window.onload = function () {
    var oneMinutes = 60 * 1,
        display = document.querySelector('#time');
    startTimer(oneMinutes, display);
};

2 个答案:

答案 0 :(得分:0)

您可以使用clearInterval来停止间隔。

function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    var handler = setInterval(function () {
        minutes = parseInt(timer / 60, 10);
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.textContent = minutes + ":" + seconds;

        if (--timer < 0) {
            clearInterval(handler);
        }
    }, 1000);
}

答案 1 :(得分:0)

到达00后,您需要clearinterval。并使用此功能点击功能

onclick="startTimer(60,document.querySelector('#time'))"

&#13;
&#13;
function startTimer(duration, display) {
  var timer = duration,
    minutes, seconds;
 var timers = setInterval(runner, 1000);
 function runner() {
    minutes = parseInt(timer / 60, 10);
    seconds = parseInt(timer % 60, 10);

    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;

    display.textContent = minutes + ":" + seconds;

    if (--timer < 0) {
       clearInterval(timers)
    }
  }

}

window.onload = function() {
  var oneMinutes = 60 * 1,
    display = document.querySelector('#time');
  startTimer(oneMinutes, display);
};
&#13;
<body>
  <div>
    <div class="timer">Battle time: <span id="time"></span></div>
    <p>BATTLE</p>
    <BUTTON class="begin" onclick="startTimer(60,document.querySelector('#time'))"><b>START</b></BUTTON>
  </div>
</body>
&#13;
&#13;
&#13;