如何在特定时间段内调用Ajax请求?

**我有一个棘手的问题,就是我想每小时拨打一次ajax电话。我不想在那个小时内发出第6个请求。但是在一个小时之后,我再次再次进行5次ajax呼叫一小时。我正在使用jquery我写的一些代码如下。有什么帮助吗? **

function getBubbles(){ $.ajax({ type : 'POST', url : '/PostData', data : data, success : function(response){ console.log(response); } }); } 

使用setTimeOut();

 $.ajax({ url: "test.html", error: function(){ // will fire when timeout is reached }, success: function(){ //do something }, timeout: 12000// sets timeout to 12 seconds }); 

这个想法怎么样?

每隔1分钟使用间隔,然后1分钟超时以防止双重请求。

每小时要求5次

 var startRequest = setInterval(getBubbles, 60000); // change this part for time of request interval var valid_minutes = [12, 24, 36, 48, 60]; // I divided 60minutes into 5 possible/valid time. function getBubbles() { var getMinutes = new Date().getMinutes(); var is_valid = $.inArray(getMinutes, valid_minutes); //following will return -1 (if not found) because a number is being searched in an array if (is_valid >= 0) { setTimeout(fucntion( // do your ajax functions here to execute $.ajax({ type: 'POST', url: '/PostData', data: data, success: function(response) { console.log(response); } }); ), 60000); //set timeout to 60 seconds to prevent multiple request (will used to past 1 minute interval) } } 

使用名为queueRequest的函数将所有请求参数推送到队列并调用checkQueue。 checkQueue检查队列中是否有项目以及活动请求的数量是否小于5.如果满足这些条件,它会从队列中弹出一个请求并将其转换为真正的AJAX请求。 然后它将一个done处理程序附加到请求,减少活动请求计数并调用checkQueue。

 var count = 0; // Number of functions being called var funcArray = []; // Array of functions waiting var MAX_REQUESTS = 5; // Max requests var CALL_WAIT = 100; // 100ms function call() { // Check if count doesn't exceeds or if there aren't any functions to call if(count >= MAX_REQUESTS || funcArray.length == 0) // Call call() after 100ms setTimeout(function() { call() }, CALL_WAIT); count++; // Add request to the counter var func = funcArray.pop(); $.ajax(..., function(data) { func(data); // ....... count--; // Substract request to the counter }); } $(function() { call(); // First call to start polling. It will call itself each 100ms }); $(function() { $("div.server").each(function() { funcArray.push(function(data) { alert(data); }); }); });