Suspend Javascript Timer

How do I pause this timer? And if he stopped, how to pause and continue counting? This should be a function

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>
      

Run codeHide result


+3


source to share


2 answers


You can do this by storing the result setInterval

in a variable:

var timeKeeper = setInterval(countdown, 1000);

      

Then when you want to pause, use clearInterval

:



clearInterval(timeKeeper);

      

This will stop the execution of the interval. To start over, reset the timer variable:

timeKeeper= setInterval(countdown, 1000);

      

0


source


Use a flag pause

with a click event by clicking the toogle pause button:

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

      

Then check if !pause

and time> 0 then decrease the time by 0.1 s

If time is <= 0 to remove the interval, just call clearInterval(setInt)

(note that you need to define it as first let setInt = setInterval(countdown, 100);

)



Using 100ms because the best precision when paused, otherwise after clicking your clock will still run the next second and then stop.

If !pause

, then it $time = $time - 0.1;

will continue. Otherwise, keep the same time and go to the next call.

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);
      

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

Run codeHide result


0


source







All Articles