最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - kill JavaScript recursive function - Stack Overflow

programmeradmin0浏览0评论

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

function foo(){
      // ajax call
      //in ajax 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

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

function foo(){
      // ajax call
      //in ajax 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

Share Improve this question asked Jun 3, 2011 at 8:35 GowriGowri 16.9k27 gold badges102 silver badges162 bronze badges 1
  • Did you try to put that condition into the success callback function? – Gumbo Commented Jun 3, 2011 at 8:37
Add a ment  | 

3 Answers 3

Reset to default 6

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)

  1. 暂无评论