如何在 clearInterval() 之后启动一个 eggtimer?

How to start a eggtimer after clearInterval()?

A 有一个可以在点击按钮 "stop" 后停止的蛋定时器。我想要的是在确认框中单击 "cancel" 后让这个计时器再次工作(从它停止的地方开始)。有什么建议吗?感谢您的帮助:)

<!DOCTYPE html>
<html>
<body onload="timer();">
<button onclick="exit();">stop</button>
    <p id="seconds">30</p>

    <script type="text/javascript">
        var clock;



        function timer () {
            var start = new Date().getTime();
            clock = setInterval(function() {
                var seconds = Math.round(30 - (new Date().getTime() - start) / 1000);
                if (seconds >= 0)
                    document.getElementById('seconds').innerHTML = seconds;
                else 
                    clearInterval(clock);



                    if (seconds==0) {window.location.href="something.com";
                    return;
                    }




            }, 1000);
        }

function exit(){

 clearInterval(clock);

var result = confirm("Are you leaving?");
if (result == true) {
window.location.href="somewhere.com";
}
else {
timer();} // <-- ????
}


    </script>
</body>
</html>

这是一个工作示例。
我将 seconds 变量移到了函数之外,因此它会持续存在并可用于 re-start 计时器。
此外,我向 timer() 函数添加了一个参数,以便可以更改倒计时数额。

请注意,粒度为秒级,因此实际倒计时最终可能会超过 30 秒,但我相信在这种用例中可以接受。

var clock;
var seconds;

function timer(wait) {
  var start = new Date().getTime();
  clock = setInterval(function() {
    seconds = Math.round(wait - (new Date().getTime() - start) / 1000);
    if (seconds >= 0)
      document.getElementById('seconds').innerHTML = seconds;
    else
      clearInterval(clock);

    if (seconds == 0) {
      window.location.href = "something.com";
      return;
    }
  }, 1000);
}

function exit() {

  clearInterval(clock);

  var result = confirm("Are you leaving?");
  if (result == true) {
    window.location.href = "somewhere.com";
  } else {
    timer(seconds);
  } // <-- ????
}

timer(30);
<button onclick="exit();">stop</button>
<p id="seconds">30</p>

您可以创建一个变量来保存您现在的秒数;

var sec  = seconds;

将您的功能timer更改为您要启动的计时器作为参数

function timer (time)

var clock;
var sec;


function timer (time) {
  var start = new Date().getTime();
  clock = setInterval(function() {
    var seconds = Math.round(time - (new Date().getTime() - start) / 1000);
    sec = seconds;
    if (seconds >= 0){
      document.getElementById('seconds').innerHTML = seconds;
    }
    else{
      clearInterval(clock);
    }
    if (seconds==0){
      window.location.href="something.com";
      return;
    }
  }, 1000);
}

function exit(){
  clearInterval(clock);
  var result = confirm("Are you leaving?");
  if (result == true) {
    window.location.href="somewhere.com";
  }
  else {
  console.log(sec);
    timer(sec);} // <-- ????
}
<body onload="timer(30);">
  <button onclick="exit();">stop</button>
  <p id="seconds">30</p>
</body>