使用的setTimeout控制轮询间隔jQuery的递归阿贾克斯调查递归、间隔、setTimeout、阿贾克斯

2023-09-10 13:45:17 作者:晃晃小脚脚

$(document).ready(function() {
    (function poll() {
        setTimeout(function() {
            $.ajax({
                url: "/project1/api/getAllUsers",
                type: "GET",
                success: function(data) {
                    console.log("polling");
                },
                dataType: "json",
                complete: poll,
                timeout: 5000
            }), 5000
        });
    })();
});​

这只是不断执行一样快,服务器可以响应,但我希望它只会轮询每5秒。有什么建议?

This just keeps executing as fast as the server can respond but I was hoping it would only poll every 5 seconds. Any suggestions?

编辑:我要补充,5秒钟后该请求已完成将是preferable

I should add, 5 seconds after the request has completed would be preferable.

推荐答案

看来你已经成功地得到您的的setTimeout 延迟参数写在错误的地方。

It seems that you've managed to get your setTimeout delay argument written in the wrong place.

$(document).ready(function() {
  (function poll() {
    setTimeout(function() {
        $.ajax({
            url: "/project1/api/getAllUsers",
            type: "GET",
            success: function(data) {
                console.log("polling");
            },
            dataType: "json",
            complete: poll,
            timeout: 5000
        }) //, 5000  <-- oops.
    }, 5000); // <-- should be here instead
  })();
});​

如果您按照括号,你会看到你调用的setTimeout 这样的:

If you follow the braces, you'll see that you're calling setTimeout like:

setTimeout(function () {
    $.ajax(), 5000
})

和应

setTimeout(function () {
    $.ajax();
}, 5000)

本应在5秒后,previous一个人完成调用AJAX调查。

This should call the AJAX poll 5 seconds after the previous one has completed.