开发者

Is there any way to kill a setInterval loop through an Onclick button

开发者 https://www.devze.com 2022-12-30 01:44 出处:网络
So, I got an infinite loop to work in this function using setInterval attached to an onClick. Problem is, I can\'t stop it using clearInterval in an onClick. I think this is because when I attach a cl

So, I got an infinite loop to work in this function using setInterval attached to an onClick. Problem is, I can't stop it using clearInterval in an onClick. I think this is because when I attach a clearInterval to an onClick, it kills a specific interval and not the function altogether. Is there anything I can do to kill all intervals through an onClick?

Here's my .js file and the calls I'm making are

input type="button" value="generate" onClick="generation();

input type="button" value="Infinite Loop!" onclick="setInterval('generation(开发者_开发技巧)',1000);"

input type="button" value="Reset" onclick="clearInterval(generation(),80;" // This one here is giving me trouble.


setInterval returns a handle, you need that handle so you can clear it

easiest, create a var for the handle in your html head, then in your onclick use the var

// in the head
var intervalHandle = null;

// in the onclick to set
intervalHandle = setInterval(....

// in the onclick to clear
clearInterval(intervalHandle);

http://www.w3schools.com/jsref/met_win_clearinterval.asp


clearInterval is applied on the return value of setInterval, like this:

var interval = null;
theSecondButton.onclick = function() {
    if (interval === null) {
       interval = setInterval(generation, 1000);
    }
}
theThirdButton.onclick = function () {
   if (interval !== null) {
       clearInterval(interval);
       interval = null;
   }
}


Have generation(); call setTimeout to itself instead of setInterval. That was you can use a bit if logic in the function to prevent it from running setTimeout quite easily.

var genTimer
var stopGen = 0

function generation() {
   clearTimeout(genTimer)  ///stop additional clicks from initiating more timers
   . . .
   if(!stopGen) {
       genTimer = setTimeout(function(){generation()},1000)
   }
}

}


Live demo

This is all you need!

<script type="text/javascript">
var foo = setInterval(timer, 1000);
function timer() {
  var d = new Date();
  var t = d.toLocaleTimeString();
  document.getElementById("demo").innerHTML = t;
}

$(document).on("click", "#stop_clock", function() {
  clearInterval(foo);
  $("#stop_clock").empty().append("Done!");
});
</script>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号