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

时间:2017-01-27 16:39:10

标签: javascript html timer user-experience

A有一个eggtimer,点击“停止”按钮后可以停止。我想要的是在确认框中单击“取消”后再次使该计时器工作(从它停止的位置)。任何sugestions?感谢您的帮助:)

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

2 个答案:

答案 0 :(得分:1)

这是一个有效的例子 我将seconds变量移到函数外部,因此它会持续存在并可用于重新启动计时器 另外,我在timer()函数中添加了一个参数,因此可以更改倒计时金额。

请注意,粒度在第二级,因此实际倒计时最终可能超过30秒,但我相信在这个用例中它是可以接受的。

&#13;
&#13;
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);
&#13;
<button onclick="exit();">stop</button>
<p id="seconds">30</p>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以创建一个在几秒钟内保存的变量;

var sec  = seconds;

使用您想要作为参数的计时器更改您的函数timer

function timer (time)

&#13;
&#13;
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);} // <-- ????
}
&#13;
<body onload="timer(30);">
  <button onclick="exit();">stop</button>
  <p id="seconds">30</p>
</body>
&#13;
&#13;
&#13;