setInterval重置循环不起作用

时间:2017-10-06 09:45:19

标签: javascript jquery

我已经创建了以下从5到0的倒计时功能,但它没有在0处重新开始倒计时。我的失败是什么?

JS:

var cc = 5;
var myTimer = setInterval(myFn, 1000);

function myFn() {
  document.getElementById("counter").innerHTML = -- cc;

  if (cc == 0) {
  clearInterval(myTimer);
  myTimer = setInterval(myFn, 1000);
  }

}

HTML:

<span id="counter">5</span>

2 个答案:

答案 0 :(得分:5)

您正在清除间隔并使用相同的回调设置另一个间隔,但您永远不会恢复cc变量的值!

var cc = 5;
var myTimer = setInterval(myFn, 1000);

function myFn() {
  document.getElementById("counter").innerHTML= --cc;

  if (cc == 0) {
    clearInterval(myTimer);
    cc = 5;
    myTimer = setInterval(myFn, 1000);
  }

}
Countdown: <span id="counter">5</span>

答案 1 :(得分:2)

var cnt = 5;
var myTimer = setInterval(myFn, 1000);

function myFn() {
  document.getElementById("counter").innerHTML= --cnt;

  if (cnt == 0) {
    clearInterval(myTimer);
    cnt= 5;
    myTimer = setInterval(myFn, 1000);
  }

}



Counter: <span id="counter">5</span>