开发者

kill JavaScript recursive function

I am having recursive function. it make calls every second. I want to kill that function in certain state.

function foo(){
      // ajax call
      //in a开发者_Python百科jax success
  success: function(response){
  setTimeout(function(){    
      foo();
   },1000);

   }  
} 

This code makes recursive call

if(user == "idile"){
//here i want to kill that foo() function
}

how can i do this ? Thanks in advance


Assign the timeout to a variable like this:

var timer;
    function foo(){
          // ajax call
          //in ajax success
      success: function(response){
      timer = setTimeout(function(){    
          foo();
       },1000);

       }  
    } 

and then to kill the timer:

if(user == "idile"){
clearTimeout(timer);
}


the way you do is using global variable,

var isFinish= false;

function foo(){
      // ajax call
      //in ajax success
  success: function(response){
  setTimeout(function(){   
      if (!isFinish)
      { 
          foo();
      }
   },1000);
   }  
} 

and then just change the isFinish to true

if(user == "idile"){
//here i want to kill that foo() function
isFinish = true;
}


When you spawn your function into a different thread, do this:

var t;

function foo()
{
    // ajax call
    //in ajax success
    success: function(response)
    {
        t = setTimeout
        (
            function(){foo();}
            ,1000
        );
    }  
} 

When you want to stop it, do this:

if(user == "idile")
{
    //here i want to kill that foo() function
    clearTimeout(t);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜