-->

JavaScript的setInterval函数明确自己?(Javascript setInterv

2019-06-27 07:09发布

myInterval = setInterval(function(){
     MyFunction();
},50);

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

间隔不是停止(不被清除),如果有什么我上面的编码是罚款那么它会帮我别处寻找什么导致的问题。 谢谢。

编辑:让我们假设它完成几个间隔clearInterval叫这消除了setTimeout的需求之前。

Answer 1:

只要你有范围,以保存interval的变量,你可以从任何地方取消。

在“儿童”的范围:

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

在“兄弟”的范围:

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

var foo = function () {
    clearInterval(myInterval);
};

你甚至可以通过的时间间隔是否会走出去的范围:

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

var foo = function (myInterval) {
    clearInterval(myInterval);
};


Answer 2:

clearInterval(myInterval);

会做的伎俩取消间隔当你需要它。 如果你想第一个电话后,立即取消,你应该采取setTimeout来代替。 并确保你可以调用它在间隔功能本身。

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

看到这里的例子 。



Answer 3:

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

要么

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


Answer 4:

从你的代码,你想要做什么,似乎是运行功能,直到一些工作已经完成一次又一次地运行它...

这实际上是对任务setTimeout()该方法是相似的:

    var myFunction = function(){
      if( stopCondition ) doSomeStuff(); //(do some stuff and don't run it again)
        else setTimeout( myFunction, 50 );
    }
    myFunction(); //immediate first run 

就那么简单 :)

当然,如果你真的想使用的setInterval出于某种原因,@ jbabey的答案似乎是最好的之一:)



Answer 5:

您可以通过使用一个技巧与window.setTimeout做

var Interval = function () {
    if (condition) {
        //do Stuff
    }
    else {
        window.setTimeout(Interval, 20);
    };
};
window.setTimeout(Interval, 20);


文章来源: Javascript setInterval function to clear itself?