1

不确定我的问题是否正确,但我有下面的代码。基本上想发出一个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();
4

2 回答 2

2

只是增加超时的延迟:

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();

这里真的不需要超时。

于 2012-05-21T22:28:11.957 回答
0

只需使用以下代码更改行:

setTimeout(govoters, 150);

和:

setTimeout(govoters, 1000); // 1 second
于 2012-05-21T22:31:57.183 回答