不确定我的问题措辞是否正确,但我有下面的代码。基本上想要发出 ajax 请求,检查回调,并重新执行 ajax 直到它获得所需的响应(在示例中 connectedvoter==1)。
问题是它只需要大约 80 毫秒,并且 xhr 的数量以这种速度非常快地达到巨大的数字。我试图想出一种“暂停”的方法,但我能想到的所有方法都耗尽了 CPU。
有没有办法“减慢”发出的请求量,比如一两秒一次而不耗尽 cpu?
var connctedvoter = 0;
var govoters = function () {
$.ajaxSetup({
async: false
});
var url = "getconnectedvoter.php";
var data = {
userid: userid
};
$.getJSON(url, data, callback);
};
var pausevoters = function () {
console.log("pausing ajax voters");
};
var callback = function (response) {
if (response.error) {
return;
}
if (response.connectedvoter == 0) {
setTimeout(govoters, 150);
//govoters();
} else {
$('#vanid').html(response.vanid);
$('#name').html(response.name);
$("#mapurl").attr("src", response.mapurl);
$('.call').fadeIn();
return;
}
};
//DO THIS TO START
setTimeout(govoters, 150);
pausevoters();
最佳答案
只是增加超时的延迟:
if(!response.connectedvoter) {
setTimeout(govoters, 2000); // instead of 150
}
而不是每秒 10 个请求:
setTimeout(govoters, 150); // one request every 150 millisecond.
请注意,开始时您可以更改为:
//DO THIS TO START
setTimeout(govoters, 150);
对此:
//DO THIS TO START
govoters();
这里真的不需要超时。
关于javascript - 减慢 ajax 调用/xhr 请求的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10693475/