2012-07-17 136 views
1

執行功能假設我有一些文件:server.php,client.php和一個表:用戶[ID,名稱,狀態]停止在setInterval的

server.php將處理像出頭:更新用戶狀態,等等......

在client.php我有一個AJAX調用server.php爲如果狀態被激活(以每10秒)檢查:

$(document).ready(function(){ 
    setInterval(function(){ 
     check_user_status(user_id) 
    },10000); 
}); 

check_user_status = function (user_id) { 
    $.ajax({ 
     type: "post", 
     data: "user_id="+user_id, 
     url : "server.php", 
     success: function(data){ 
      // do something with the response 
      // I want to exit the checking operation if user is already activated 
     }, 
     error: function(e){ 
      alert("Error occurred"); 
     } 
    }); 
} 

怎麼能做到呢?

謝謝你的時間!

+0

[clearInterval(https://developer.mozilla.org/en/window.clearInterval)是啓動的 – andyb 2012-07-17 10:32:40

+0

可能重複的好去處[如何阻止 「的setInterval」] (http://stackoverflow.com/questions/1831152/how-to-stop-setinterval) – andyb 2012-07-17 10:34:01

回答

5

記得已經給你的計時器ID:

var timer = setInterval(...); 

,然後取消它,當條件滿足:

clearInterval(timer); 

timer變量將需要在「範圍」 - 最簡單的解決方案是將所有的代碼放入document.ready處理程序中。

FWIW,實際上最好使用setTimeout而不是setInterval,然後每次重新啓動計時器。

setInterval會導致問題,如果您的服務器無響應,因爲它會忠實地保持每10秒排隊回調。一旦服務器響應,它會突然嘗試立即運行所有回調。

改爲使用setTimeout將確保沒有新的檢查排隊,直到前一個實際完成。

+0

應該是'clearInterval(timer)',而不是'clearTimeout(timer)' – 2012-07-17 10:32:20

+0

@AlvinWong oops - 謝謝。 – Alnitak 2012-07-17 10:33:02

+0

工程就像一個魅力。非常感謝你。我接受了你的回答。 – 2012-07-17 10:40:58

1

嘗試:

var intrvl = setInterval(function(){ 
     check_user_status(user_id) 
    },10000); 


.... 
success: function(data){ 
clearInterval(intrvl); 

} 
相關問題