Javascript Countdown with Pause&恢复

时间:2016-07-23 06:45:55

标签: javascript

我有javascript倒计时

var timersCount = 0;
var timerCounter = setInterval(countTimers, 30000);
countTimers();

function countTimers()
{
    timersCount++;

    var count = 26;
    var counter = setInterval(timer, 1000);
    function timer()
    {

        count = count-1;
        if(count < 0) {
         clearInterval(counter);
         return;
        }

        document.getElementById("timer").innerHTML=count;
    }

document.getElementById("countTimers").innerHTML=timersCount;
}

HTML

<button id="pause">Pause</button>
<button id="resue">Resume</button>

该功能正常运行。但现在我想添加Pause并恢复倒计时。是否可以将其设置为我的功能。请帮忙。

1 个答案:

答案 0 :(得分:2)

你走了。首先,你只需要一个间隔,第二个你应该有一些标志告诉你何时暂停计时器。然后它只是简单的逻辑和2个听众。

&#13;
&#13;
var timersCount = 0;
var pause = false; //is timer paused

countTimers();

function countTimers() {
  timersCount++;

  var count = 26;
  var counter = setInterval(timer, 1000);

  function timer() {
    if (!pause) { //do something if not paused
      count = count - 1;
      if (count < 0) {
        clearInterval(counter);
        setTimeout(countTimers, 5000); //start count from 26 again
        return;
      } 

      document.getElementById("timer").innerHTML = count;
    }
  }

  document.getElementById("countTimers").innerHTML = timersCount;
}

document.getElementById('pause').addEventListener('click', function () {
	pause = true;
});

document.getElementById('resume').addEventListener('click', function () {
	pause = false;
});
&#13;
<span id="timer"></span>
<span id="countTimers"></span>
<button id="pause">Pause</button>
<button id="resume">Resume</button>
&#13;
&#13;
&#13;