重复setInterval

时间:2016-10-05 09:11:34

标签: javascript html

我目前正在JavaScript中使用setInterval函数来处理HTML页面。它有一个按钮,允许我以1秒的间隔开始从10到0的倒计时,每次按下按钮,倒计时应该重置。然而,按下第一个按钮后,下一个倒计时会严重扰乱间隔。

var count;

function countdown() {
  count = 10;
  var repeat = setInterval(reduce, 1000);
}

function reduce() {
  if (count > 0) {
    document.getElementById('number').innerHTML = count;
    count--;
  } else {
    clearInterval(repeat);
  }
}
<html>
<head>
  <title>Page 4</title>
</head>
<body>
  <button style=" display: inline-block; " onclick="countdown()">Start Count Down</button>
  <div style=" display: inline-block;" id="number"></div>
</body>
</html>

4 个答案:

答案 0 :(得分:0)

您的问题是repeat变量,它是在countdown内定义和访问的。
您也可以将其设为全局,然后再次单击该按钮时必须清除之前的间隔

var count, repeat;

function countdown() {
    clearInterval(repeat);
    count = 10;
    repeat = setInterval(reduce, 1000);
}

function reduce() {
    if (count > 0) {
        document.getElementById('number').innerHTML = count;
        count--;
    } else {
        clearInterval(repeat);
    }
}

FIDDLE

答案 1 :(得分:0)

将你的重复放在外面,所以函数reduce可以访问它

    var count;
    var repeat = null;
    function countdown(){

      count = 10;
      repeat = setInterval(reduce, 1000);


    }

    function reduce() {
      if(count > 0)
      {document.getElementById('number').innerHTML = count;
      count--;}
      else
      {clearInterval(repeat);}


    }

答案 2 :(得分:0)

您可以使用全局变量repeat,并在调用倒计时时设置为重置。

var count,
    repeat;

function countdown(){     
    count = 10;
    if (repeat) {
        clearInterval(repeat);
    }
    repeat = setInterval(reduce, 1000);     
}

function reduce() {
    if (count > 0) {
        document.getElementById('number').innerHTML = count;
        count--;
    } else {
        clearInterval(repeat);
    }
}
<button style=" display: inline-block; " onclick ="countdown()" >Start Count Down</button>
<div style="display: inline-block;" id="number"></div>

答案 3 :(得分:0)

您也可以使用this来停止间隔;

clearInterval(this)

var count;

function countdown() {
  count = 10;
  var repeat = setInterval(reduce, 1000);
}

function reduce() {
  if (count > 0) {
    document.getElementById('number').innerHTML = count--;
  } else {
    clearInterval(this);
  }
}
<button style=" display: inline-block; " onclick="countdown()">Start Count Down</button>
<div style=" display: inline-block;" id="number"></div>

这将解决您的问题,但会引发另一个问题。如果多次单击,将注册多个事件。为此,您应该禁用按钮或在父范围中定义repeat

var count, repeat;

function countdown() {
  count = 10;
  repeat = repeat || setInterval(reduce, 1000);
}

function reduce() {
  if (count > 0) {
    document.getElementById('number').innerHTML = count--;
  } else {
    clearInterval(this);
  }
}
<button style=" display: inline-block; " onclick="countdown()">Start Count Down</button>
<div style=" display: inline-block;" id="number"></div>

您会注意到一个简单的伎俩:

repeat = repeat || setInterval(reduce, 1000);

这将确保不会注册多个间隔。