Javascript setInterval function to clear itself?

user1017882 picture user1017882 · Aug 23, 2012 · Viewed 56.3k times · Source
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.

Answer

jbabey picture jbabey · Aug 23, 2012

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