Javascript setInterval function to clear itself?

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

    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.

提交回复
热议问题