Javascript setInterval function to clear itself?

荒凉一梦 提交于 2019-11-29 22:04:50

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);
};
clearInterval(myInterval);

will do the trick to cancel the Interval whenever you need it. If you want to immediately cancel after the first call, you should take setTimeout instead. And sure you can call it in the Interval function itself.

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

see an EXAMPLE here.

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

From your code what seems you want to do is to run a function and run it again and again until some job is done...

That is actually a task for the setTimeout(), the approach is similar:

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

Simple as that :)

Of course if you REALLY want to use setInterval for some reason, @jbabey's answer seems to be the best one :)

You can do it by using a trick with window.setTimeout

var Interval = function () {
    if (condition) {
        //do Stuff
    }
    else {
        window.setTimeout(Interval, 20);
    };
};
window.setTimeout(Interval, 20);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!