Javascript计时器暂停&恢复

时间:2017-09-08 12:14:48

标签: javascript

代码如下。

如何添加暂停功能并停止计时器,还设置按钮暂停计时器并在按下恢复时恢复?

// startTimer将启动正文的计时器onload。

 function startTimer() {

    userInput = "35";

    if(userInput.length == 0){
        alert("Please enter a value");
    } 
    else {
        var numericExpression = /^[0-9]+$/;
        if(!userInput.match(numericExpression)){
        alert("Please enter a number")
        }       
        else {
        function display( notifier, str ) {
        document.getElementById(notifier).innerHTML = str;
            }

        function toMinuteAndSecond( x ) {
         return Math.floor(x/60) + ":" + x%60;
  }

  function setTimer( remain, actions ) 
  {

    (function countdown() 
        {
       display("countdown", toMinuteAndSecond(remain));         
       actions[remain] && actions[remain]();
       (remain -= 1) >= 0 && setTimeout(arguments.callee, 1000);
        })();
  }


  setTimer(userInput, {
    35: function () { display("score", "6"); document.getElementById("total").value = 6 },
    20: function () { display("score", "4"); document.getElementById("total").value = 4 },
    15: function () { display("score", "3"); document.getElementById("total").value = 3 },
    10: function () { display("score", "2"); display("notifier", "10 seconds left"); document.getElementById("total").value = 2 },
     5: function () { display("score", "1"); display("notifier", "5 seconds left"); document.getElementById("total").value = 1 },
     0: function () { display("score", "0"); display("notifier", "Time is up"); document.getElementById("total").value = 0 },
  }); 
}  
}
}

// setTimer设置倒计时并在页面上显示时间。

// setTimer(userInput)是在计时器范围内随机显示得分,因为计时器更改得分也会发生变化。

在某些限制下,我需要暂停计时器,每当我停止计时器时,计时器将显示正确的分数。

感谢您的帮助!!

1 个答案:

答案 0 :(得分:1)

这为您提供了一个基本的,可停止的定时器

HMTL:

<p>A script on this page starts this clock:</p>
<p id="demo"></p>
<p>Elapsed Seconds:</p>
<p id="secondsPassed"></p>

<button onclick="stopTimer()">Stop time</button>
<button onclick="startTimer()">Start Timer</button>
<button onclick="resumeTimer()">Resume Timer</button>

JS:

var myVar = setInterval(start ,1000);
var Seconds = 0;

function startTimer() { 
    myVar = setInterval(start ,1000);
    Seconds = 0;
}

function resumeTimer() {    
    myVar = setInterval(start ,1000);
}

function start() {
    var d = new Date();
    document.getElementById("demo").innerHTML = d.toLocaleTimeString();
    Seconds++;
    document.getElementById("secondsPassed").innerHTML = Seconds;
}

function stopTimer() {
    clearInterval(myVar)
}

编辑自:https://www.w3schools.com/js/tryit.asp?filename=tryjs_setinterval3

教程:https://www.w3schools.com/js/js_timing.asp