Javascript setInterval function to clear itself?

前端 未结 5 926
离开以前
离开以前 2020-12-23 19:17
myInterval = setInterval(function(){
     MyFunction();
},50);

function MyFunction()
{
    //Can I call clearInterval(myInterval); in here?
}

The

5条回答
  •  别那么骄傲
    2020-12-23 19:42

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

提交回复
热议问题