如何在几轮后停止倒计时?

时间:2016-12-02 16:00:18

标签: javascript html

var secondsP = document.getElementById('seconds');
var btn1 = document.getElementById("btnSurrender");
var clock = null;

btn1.addEventListener("click", surrender);

function timer () {

clearInterval(clock);

var start = new Date().getTime();

clock = setInterval(function() {




         var seconds = Math.round(15 - (new Date().getTime() - start) / 1000);


         if (seconds >= 0) {
           secondsP.textContent = seconds;
         } else {
           clearInterval(clock);
         }

         if (seconds === 0) {


         }
}, 1000);
}



function surrender(){

clearInterval(clock);
secondsP.textContent = 0;
setTimeout(timer,2000);
}


timer();
setInterval(timer, 17000);
<html>
<head>
<style>

</style>
<script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
</head>
<body> 
<p id="seconds">15</p>
<button id= "btnSurrender">end now</button>

</body>
</html>

我的小问题需要帮助。我制作了一个秒表倒计时15秒。在这15秒后,它等待两秒钟然后重新开始。您可以选择在需要时停止计数,使用“立即结束”按钮(然后它将在2秒后重新开始)。现在,我的问题是:如何在3/4轮之后制作一个能够停止全部计数的功能?

1 个答案:

答案 0 :(得分:0)

使用通话surrender()重启setTimeout(timer, 2000)中的时钟。您需要做的就是在该函数内添加一个if statement来测试一个变量,该变量控制您运行计时器的次数,然后相应地调用/不调用timer()。以下是它的一个实例:https://jsfiddle.net/L38q6k5d/,但只是为了让您了解它是如何工作的:

在js文件的顶部:

var timesRun = 0
var timerInterval = null;

surrender函数内:

timesRun += 1 // Increment it each time the timer ends
if (timesRun > 4) { // If the timer has run less than 4 times
    return; // this will stop the function here, so we dont start the timer again
}     
setTimeout(timer, 2000); // Reset the timer

timer函数内,

if (timesRun > 1) {
    clearInterval(timerInterval);
    return; // end the function here
}

启动初始计时器时:

timer();
timerInterval = setInterval(timer, 17000);

完成JS:

var secondsP = document.getElementById('seconds');
var btn1 = document.getElementById("btnSurrender");
var clock = null;
var timerInterval = null;
// New Code
var numberOfTimesRun = 0; // this is where we keep track of how many times the timer has run

btn1.addEventListener("click", surrender);

function timer () {
    clearInterval(clock);

    // New Code
  if (numberOfTimesRun > 1) {
    clearInterval(timerInterval);
    return; // end the function here
  }
  // End New Code

  var start = new Date().getTime();

  clock = setInterval(function() {

    var seconds = Math.round(15 - (new Date().getTime() - start) / 1000);

    if (seconds >= 0) {
      secondsP.textContent = seconds;
    } else {
      clearInterval(clock);
        numberOfTimesRun += 1; // so we know that 1 iteration of the timer has been completed
    }

    if (seconds === 0) {
    }

    }, 1000);
}



function surrender(){
  clearInterval(clock);
  secondsP.textContent = 0;
  //New Code
    numberOfTimesRun += 1;
  if (numberOfTimesRun > 4) {
    return; // end the function there
  }
  setTimeout(timer, 2000)
  //End New Code
}


timer();
timerInterval = setInterval(timer, 17000);