Javascript setInterval function to clear itself?

前端 未结 5 932
离开以前
离开以前 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:28

    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 context
    var interval = setInterval(callback, 50);
    

提交回复
热议问题