2012-12-07 134 views
0

我有一個poll()功能:如何停止多次執行javascript函數(輪詢)?

$("document").ready(function(){ 
    poll(10); 
    $("#refresh").click(function(){ poll(10); }); 
}); 

function poll(timeout){ 
    return setTimeout(function(){ 
     if (timeout == 10){ 
     timeout = 10000; 
     } 
     $.ajax({ url: "/ajax/livedata.php", success: function(data){ 
     $("#result").html(data); 
     poll(timeout); 
     }, dataType: "json"}); 
    }, timeout); 
} 

那麼,會發生什麼情況出現:在頁面加載

1),poll()被調用,在循環開始執行。

2)在#refresh點擊,poll()在那一刻被調用以立即請求新數據。

問題:每當我點擊#refresh請求新的數據時,poll()再次調用,但發射多次(第一次初始+每一個新的點擊)。因此,它不像預期的那樣每10秒發射一次,而是每10秒發射多次(取決於我點擊#refresh的次數)。

我該如何解決這個問題,以便每當我點擊#refresh時,只剩下1個實例將循環?

回答

0

第一家店你setTimeout對象有點像這個

var a = poll(10); 

然後一個變量停止它在通過使用此代碼點擊刷新

clearTimeout(a); 

因此,這將是這個樣子

$("document").ready(function(){ 
    var a = null; 
    $("#refresh").click(function(){ 
     if(a != null){ 
      clearTimeout(a); 
      a = null; 
     } 
     a = poll(10); 
    }); 
}); 

參考:

http://www.w3schools.com/jsref/met_win_cleartimeout.asp

http://www.w3schools.com/js/tryit.asp?filename=tryjs_timing_stop

+0

這看起來正是我需要的,但出於某種原因,clearTimeout(a)是無法摧毀的setTimeout對象。 –

+0

@RiMMER也許@Mahan正在考慮'setInverval' /'clearInterval' – McGarnagle

+0

@RiMMER請檢查我提的參考 –