如何在0:00停止计时器循环?

时间:2017-11-24 21:41:08

标签: javascript

当它结束时它会继续循环。我如何阻止它以及如何创建和警告游戏结束?

if(levelOption === 0) {
    time = 60 * 0.1, g = document.getElementById('g'), tmp = time;
    setInterval(function() {
        var c = tmp--, m = (c/60) >> 0, s = (c-m*60) + '';
        g.textContent = '' + m + ':' + (s.length > 1 ? '' : '0') + s tmp != 0 || (tmp = time); 
    }, 1000);
} else if(levelOption === 1) {
    time = 60 * 10, g = document.getElementById('g'), tmp = time;
    setInterval(function(){
        var c = tmp--, m = (c/60) >> 0, s = (c-m * 60) + '';
        g.textContent = '' + m + ':' + (s.length > 1 ? '' : '0') + s tmp != 0 || (tmp = time); 
    }, 1000);
} else {
    time = 60 * 20, g = document.getElementById('g'), tmp = time;
    setInterval(function() {
        var c = tmp--, m = (c/60) >> 0, s = (c-m * 60) + '';
        g.textContent = '' + m + ':' + (s.length > 1 ? '' : '0') + s tmp != 0 || (tmp = time); 
    }, 1000);
}

2 个答案:

答案 0 :(得分:0)

  1. 将setInterval值保存到某个变量,例如display:none
  2. 在时间函数中,如果时间< = 0,请执行Qt Documentation let interval = setInterval;

答案 1 :(得分:0)

如果您首先通过将间隔保存到变量(var myCounter = setInterval(...))来命名间隔,则可以稍后使用clearInterval(myCounter)清除间隔。

我不知道您在哪个环境中使用这些计数器,但我认为您可以简化逻辑。看看这个计数器是否适合你:



time = 3,
g = document.getElementById('g'),
tmp = time;

// Here we name our interval
var myCounter = setInterval(function() {

  // Clear the interval if our counter has reached 0
  if(tmp == 0) clearInterval(myCounter)

  // Set minute and second values
  var m = (tmp / 60) >> 0,
      s = tmp - m * 60;

  // Print values
  g.textContent = m + ':' + ((s>9)?'':'0') + s;

  // Finish of with modifying the counter
  tmp--;
}, 1000);

<div id="g"></div>
&#13;
&#13;
&#13;