Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to start and stop/pause setInterval?

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 :

input = document.getElementById("input");    function start() {    add = setInterval("input.value++", 1000);  }  start();
<input type="number" id="input" />  <input type="button" onclick="clearInterval(add)" value="stop" />  <input type="button" onclick="start()" value="start" />

Is there a working way to do this?

like image 635
Web_Designer Avatar asked Dec 16 '11 19:12

Web_Designer


People also ask

How do you stop and start setInterval?

Answer: Use the clearInterval() Method The setInterval() method returns an interval ID which uniquely identifies the interval. You can pass this interval ID to the global clearInterval() method to cancel or stop setInterval() call.

How do you stop setInterval from inside?

Stop setInterval() Using clearInterval() Function in JavaScript. The setInterval() function is used to call a function or execute a piece of code multiple times after a fixed time delay. This method returns an id that can be used later to clear or stop the interval using clearInterval() .


1 Answers

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" />
like image 194
jessegavin Avatar answered Sep 19 '22 12:09

jessegavin