javascriptsetinterval

How can I pause setInterval() functions?


How do I pause and resume the setInterval() function using Javascript?

For example, maybe I have a stopwatch to tell you the number of seconds that you have been looking at the webpage. There is a 'Pause' and 'Resume' button. The reason why clearInterval() would not work here is because if the user clicks on the 'Pause' button at the 40th second and 800th millisecond, when he clicks on the 'Resume' button, the number of seconds elapsed must increase by 1 after 200 milliseconds. If I use the clearInterval() function on the timer variable (when the pause button is clicked) and then using the setInterval() function on the timer variable again (when the resume button is clicked), the number of seconds elapsed will increase by 1 only after 1000 milliseconds, which destroys the accuracy of the stopwatch.

So how do I do that?


Solution

  • You could use a flag to keep track of the status:

    var output = $('h1');
    var isPaused = false;
    var time = 0;
    var t = window.setInterval(function() {
      if(!isPaused) {
        time++;
        output.text("Seconds: " + time);
      }
    }, 1000);
    
    //with jquery
    $('.pause').on('click', function(e) {
      e.preventDefault();
      isPaused = true;
    });
    
    $('.play').on('click', function(e) {
      e.preventDefault();
      isPaused = false;
    });
    h1 {
        font-family: Helvetica, Verdana, sans-serif;
        font-size: 12px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <h1>Seconds: 0</h1>
    <button class="play">Play</button>
    <button class="pause">Pause</button>

    This is just what I would do, I'm not sure if you can actually pause the setInterval.

    Note: This system is easy and works pretty well for applications that don't require a high level of precision, but it won't consider the time elapsed in between ticks: if you click pause after half a second and later click play your time will be off by half a second.