2011-06-03 69 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); 
}