暂停Javascript计时器

时间:2017-05-22 22:46:41

标签: javascript jquery

如何暂停此计时器?如果它暂停如何取消暂停并继续计数?它应该是一个函数

function timer($time) {
    let $lorem = $("#lorem");
    function countdown() {
      let $minutes = Math.floor($time / 60);
      let $seconds = $time % 60;
      let $result = $minutes + ":" + ($seconds < 10 ? "0" + $seconds : $seconds);
      --$time;
      $lorem.text($result);
    }
    countdown();
    setInterval(countdown, 1000);
  }
  timer(200);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="lorem"></div>

2 个答案:

答案 0 :(得分:0)

您可以将setInterval的结果存储在变量中来执行此操作:

var timeKeeper = setInterval(countdown, 1000);

然后,当您想要暂停时,请使用clearInterval

clearInterval(timeKeeper);

这将停止执行间隔。要重新开始,请重置计时器变量:

timeKeeper= setInterval(countdown, 1000);

答案 1 :(得分:0)

在点击停留时使用带有点击事件的标记pause

  let pause = false;
  $lorem.on('click', function() {
    pause = !pause;
  });

然后检查!pause和时间&gt; 0然后将时间减少0.1s

如果时间&lt; = 0删除时间间隔,只需拨打clearInterval(setInt)(请注意,您需要先将其定义为let setInt = setInterval(countdown, 100);

使用100ms因为暂停时精度更高,否则点击后,你的时钟仍会在下一秒进入,然后停止。

如果!pause,则$time = $time - 0.1;继续。否则保持相同的时间并转到下一个电话。

&#13;
&#13;
function timer($time) {
  let $lorem = $("#lorem");
  let pause = false;
  let setInt = setInterval(countdown, 100);
  $('#pause').on('click', function() {
    pause = !pause;
  });

  function countdown() {
    if (!pause && $time > 0) {
      $time = ($time - 0.1).toFixed(1);
    }
    if($time <= 0){
      clearInterval(setInt);
    }

    let $minutes = Math.floor($time / 60);
    let $seconds = Math.ceil($time % 60);
    let $result = $minutes + ":" + ($seconds < 10 ? "0" + $seconds : $seconds);

    $lorem.text($result);
    console.log($time);
  }

}
timer(3);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="lorem"></div>

<br>
<button id="pause">Pause</button>
&#13;
&#13;
&#13;