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

标签 javascript html timer user-experience

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

<!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>

最佳答案

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

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>

关于javascript - 如何在 clearInterval() 之后启动一个 eggtimer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41898801/

相关文章:

c++ - 正确实现 Timer1 以生成 PWM

javascript - 如何为图像设置计时器以在 javascript 或 html 中显示?

javascript - 在 for 之后的 if 语句中使用对象 item

javascript - mouseenter 同时显示 :none is set

javascript - react 组件DidUpdate : check wether state OR props change caused the update?

javascript - 按钮单击以替换图像

javascript - 如何更改js中已由php设置的cookie?

javascript - 如何使用javascript将文本输入的值存储为字符串

html - 以干净的方式对齐/堆叠大量小但大小不同的 div 框

c - Arduino 问题 : Using TimerOne and delayMicroseconds()