Javascript clearInterval用法

时间:2014-10-18 13:07:05

标签: javascript html5

我有以下代码用于创建计数器的计时器:

<h1><label id="minutes">00</label>:<label id="seconds">00</label></h1>
<button onclick="loadHard()">Reset All</button>

<script type="text/javascript">
function loadHard() {
drawImage('image.png', 268, 5);
console.log('idle');
clearInterval(setTime);
}

var minutesLabel = document.getElementById("minutes");
var secondsLabel = document.getElementById("seconds");
var totalSeconds = 0;
setInterval(setTime, 1000);

function setTime()
{
++totalSeconds;
secondsLabel.innerHTML = pad(totalSeconds%60);
minutesLabel.innerHTML = pad(parseInt(totalSeconds/60));
}

但是,当我单击“全部重置”按钮时,计时器会继续计数并且不会重置为0.有没有办法将计时器重置为0,我不知道这个?

4 个答案:

答案 0 :(得分:3)

clearInterval没有功能。它需要一张&#34;机票&#34;或者#34;注册&#34;或者你想称之为什么。基本上,您需要保存setInterval的结果,如下所示:

var ticket;
function test() {
    console.log('running test');
}

function schedule() {
    ticket = setInterval(test, 1000);
}

function unschedule() {
    clearInterval(ticket);
}

答案 1 :(得分:0)

以下是如何做到的:

function loadHard() {
    drawImage('image.png', 268, 5);
    console.log('idle');
    // Clears the interval based on the id
    clearInterval(intervalId);
    // This will reset
    minutesLabel.innerHTML = secondsLabel.innerHTML = "00";
}

var minutesLabel = document.getElementById("minutes");
var secondsLabel = document.getElementById("seconds");
var totalSeconds = 0;
// Notice we assign setInterval to an id
// The id can be used to clear the interval
var intervalId = setInterval(setTime, 1000);

function setTime()
{
    ++totalSeconds;
    secondsLabel.innerHTML = pad(totalSeconds%60);
    minutesLabel.innerHTML = pad(parseInt(totalSeconds/60));
}

或者,如果你只想重置计时器但保持时钟滴答,你可以这样做:

function loadHard() {
    drawImage("image.png", 268, 5);
    totalSeconds = -1;
    setTime(); // Updates the time to 0
}

答案 2 :(得分:0)

使用此

<h1><label id="minutes">00</label>:<label id="seconds">00</label></h1>
<button onclick="loadHard()">Reset All</button>

<script type="text/javascript">
var timeout;
function loadHard() {
drawImage('image.png', 268, 5);
console.log('idle');
clearInterval(timeout);
}

var minutesLabel = document.getElementById("minutes");
var secondsLabel = document.getElementById("seconds");
var totalSeconds = 0;

timeout=setInterval(setTime, 1000);

function setTime()
{
++totalSeconds;
secondsLabel.innerHTML = pad(totalSeconds%60);
minutesLabel.innerHTML = pad(parseInt(totalSeconds/60));
}

答案 3 :(得分:0)

像Alxandr回答: 您可以为区间分配ID,如下所示:

var ticket;
function test() {
    console.log('running test');
}

function schedule() {
    ticket = setInterval(test, 1000);
}

function unschedule() {
    clearInterval(ticket);
}

但在你的情况下,这也会做:

&#13;
&#13;
function test() {
   alert("hey");
}
 
function start(){
  setInterval(test, 0);
}
 
function unschedule() {
  for (var i = 1; i < 99; i++)
        window.clearInterval(i);
}
&#13;
&#13;
&#13;