如何在javascript中切换或暂停setInterval

时间:2017-09-23 23:57:52

标签: javascript html timer

我正在学习java脚本,我正在尝试创建时钟应该是"当我点击按钮时,时间应该停止更改,按钮应该从“停止时间”变为“开始时间”&当我再次点击按钮时,时间应该开始改变,按钮应该从“开始时间”改变为“停止时间”。查看我的代码并告诉我需要添加哪些代码或功能以及添加位置...我是新手,所以我将非常感谢您的帮助..

<!DOCTYPE html>
<html>
<body>

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

<button onclick="myStopFunction()">Stop time</button>
</body>
</html>

// ---脚本在这里---

<script>
var myVar = setInterval(function(){ myTimer() }, 1000);

function myTimer() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
}

function myStopFunction() {
clearInterval(myVar);
}
</script>

2 个答案:

答案 0 :(得分:0)

你需要一个小技巧来切换你的功能:

&#13;
&#13;
var myVar = setInterval(function () {
      myTimer()
}, 1000);
var isPaused = false;

function myTimer() {
      var d = new Date();
      var t = d.toLocaleTimeString();
      document.getElementById("demo").innerHTML = t;
}

function toggleFunction() {
      if (isPaused) {
            myVar = setInterval(function () {
                  myTimer()
            }, 1000);
            isPaused = false;
      } else {
            clearInterval(myVar);
            isPaused = true;
      }
}
&#13;
<p>A script on this page starts this clock:</p>
<p id="demo"></p>

<button onclick="toggleFunction()">Toggle time</button>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

试试这个

let currentTime = new Date();
let status = true;
let interval = 1; // in seconds
let dateFormat = { hour: 'numeric', minute:'numeric', second: 'numeric', hour12: true };

let clock = document.querySelector('#demo');
    clock.innerHTML = currentTime.toLocaleString('en-US', dateFormat);

let timer = setInterval(
    function () {
        currentTime.setSeconds(currentTime.getSeconds() + interval);
        clock.innerHTML = currentTime.toLocaleString('en-US', dateFormat);
    }, interval * 1000
);

let button = document.querySelector('#button');
    button.addEventListener('click', onClick);

function onClick() {
    if (!status) {
        button.innerHTML = 'Stop timer';

        timer = setInterval(
            function () {
                currentTime.setSeconds(currentTime.getSeconds() + interval);
                clock.innerHTML = currentTime.toLocaleString('en-US', dateFormat);
            }, interval * 1000
        );

        return;
    }

    if (status) {
        button.innerHTML = 'Start timer';
        clearInterval(timer);
    }

    status = !status;
}
<p>A script on this page starts this clock:</p>
<p id="demo"></p>

<button id="button">Stop time</button>