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?
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.
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() .
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" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With