2014-10-29 92 views
0

你好我想做一個智能輪詢功能,其中每4個空響應後間隔時間應加倍。但是如果間隔達到最大間隔,它應該只保留在該值上。應該爲它寫什麼函數。智能輪詢功能

這是從PHP代碼獲取響應的代碼。

function updateChat() { 
    console.log("inside updatechat"); 

    setInterval(function() 

     $.ajax({ 
      //type: "POST", 
      url: "file.php", 
      //data: id, 
      //dataType: JSON, 

      success: function(response) { 
       var result = JSON.parse(response); 
       //console.log("Result is " +result); 

       for (var i in result) { 

        $(".message_box").append('<p class = "shout_msg">' + result[i] + '</p>'); 
        $(".message_box").scrollTop($(".message_box")[0].scrollHeight); 
       } 

      } 


     }), interval); 

} 

我的輪詢功能是什麼?

+2

這不是PHP的,它是JavaScript的 – zavg 2014-10-29 11:50:14

回答

1

setInterval調用回調每隔一定時間間隔......你需要的是setTimeout

var INITIAL_INTERVAL = 500; // 0.5 sec 
var MAX_INTERVAL = 120000; // two minutes 
var interval = INITIAL_INTERVAL; 

var pollingFunction = function() { 
    $.ajax({ 
     //type: "POST", 
     url: "file.php", 
     //data: id, 
     //dataType: JSON, 

     success: function(response) { 
      var result = JSON.parse(response); 
      if (result.length == 0) { // or whatever condition to check return of empty result 
       // empty result - poll server at slower pace 
       interval *= 2; 
       if (interval > MAX_INTERVAL) { 
        interval = MAX_INTERVAL; 
       } 
      } 
      else { 
       // reset interval to initial quick value 
       interval = INITIAL_INTERVAL; 
      } 
      //console.log("Result is " +result); 

      for (var i in result) { 

       $(".message_box").append('<p class = "shout_msg">' + result[i] + '</p>'); 
       $(".message_box").scrollTop($(".message_box")[0].scrollHeight); 
      } 

      // activate the pollingFunction again after 'interval' ms 
      // important - set the timeout again of the polling function 
      setTimeout(pollingFunction, interval); 
     } 


    }) 
} 

// activate the polling function the first time after interval ms 
// important - set the timeout once (or call the polling function once) from outer scope. 
setTimeout(pollingFunction, interval); 
+0

嘿感謝,它爲我工作。我有一個疑問,你可以解釋這兩個setTimeout函數是如何工作的 – 2014-10-29 13:08:02

+0

我不確定你在問什麼都setTimeout - 我會嘗試修改與添加解釋的答案。如果答案適用於您,您可以將其標記爲解決方案(表決按鈕下方的複選標記),因此此問題將被標記爲「已解決」。 – Iftah 2014-10-29 15:31:06