Javascript setInterval function to clear itself?

clearinterval, javascript, setinterval

Solution

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);
};

Problem

``` myInterval = setInterval(function(){ MyFunction(); },50); function MyFunction() { //Can I call clearInterval(myInterval); in here? } ``` The interval's not stopping (not being cleared), if what I've coded above is fine then it'll help me look elsewhere for what's causing the problem. Thanks. EDIT: Let's assume it completes a few intervals before clearInterval is called which removes the need for setTimeout.

Original source

Related problems