How to start and stop/pause setInterval?

Web_Designer picture Web_Designer · Dec 16, 2011 · Viewed 116.7k times · Source

I'm trying to pause and then play a setInterval loop.

After I have stopped the loop, the "start" button in my attempt doesn't seem to work :

Is there a working way to do this?

Answer

jessegavin picture jessegavin · Dec 16, 2011

See Working Demo on jsFiddle: http://jsfiddle.net/qHL8Z/3/

$(function() {
  var timer = null,
    interval = 1000,
    value = 0;

  $("#start").click(function() {
    if (timer !== null) return;
    timer = setInterval(function() {
      $("#input").val(++value);
    }, interval);
  });

  $("#stop").click(function() {
    clearInterval(timer);
    timer = null
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" id="input" />
<input id="stop" type="button" value="stop" />
<input id="start" type="button" value="start" />