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

Gowri
  • 16,587
  • 26
  • 100
  • 160

3 Answers3

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);
}
Niklas
  • 29,752
  • 5
  • 50
  • 71
3

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;
}
kororo
  • 1,972
  • 15
  • 26
0

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);
}
shinkou
  • 5,138
  • 1
  • 22
  • 32