Javascript setInterval function to clear itself? Javascript setInterval function to clear itself? javascript javascript

Javascript setInterval function to clear itself?


As long as you have scope to the saved interval variable, you can cancel it from anywhere.

In an "child" scope:

var myInterval = setInterval(function(){     clearInterval(myInterval);},50);

In a "sibling" scope:

var myInterval = setInterval(function(){     foo();},50);var foo = function () {    clearInterval(myInterval);};

You could even pass the interval if it would go out of scope:

var someScope = function () {    var myInterval = setInterval(function(){        foo(myInterval);    },50);};var foo = function (myInterval) {    clearInterval(myInterval);};


clearInterval(myInterval);

will do the trick to cancel the Interval whenever you need it.If you want to immediately cancel after the first call, you should take setTimeout instead. And sure you can call it in the Interval function itself.

var myInterval = setInterval(function() {  if (/* condition here */){        clearInterval(myInterval);   } }, 50);

see an EXAMPLE here.


var interval = setInterval(function() {  if (condition) clearInterval(interval); // here interval is undefined, but when we call this function it will be defined in this context}, 50);

Or

var callback = function() { if (condition) clearInterval(interval); }; // here interval is undefined, but when we call this function it will be defined in this contextvar interval = setInterval(callback, 50);