2011-06-03 74 views
0

我有递归函数。它每秒都会打电话。我想在特定状态下杀死那个函数。杀JavaScript递归函数

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

    } 
} 

此代码递归调用

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

我怎么能做到这一点? 在此先感谢

+0

你尝试把这种状态变成*成功*回调函数? – Gumbo 2011-06-03 08:37:59

回答

4

指定超时给一个变量是这样的:

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

     } 
    } 

,然后杀器:

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

我喜欢你的方式,我忘了清除计时器...很好! – kororo 2011-06-03 08:41:15

3

你要做的就是使用全局变量的方式,

var isFinish= false; 

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

然后只是将isFinish更改为true

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

当你产卵的功能分为不同的线程,这样做:当你想停止它

var t; 

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

,这样做:

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