使用的setTimeout控制轮询间隔jQuery的递归阿贾克斯调查 [英] jQuery recursive ajax poll using setTimeout to control the poll interval

查看:1525
本文介绍了使用的setTimeout控制轮询间隔jQuery的递归阿贾克斯调查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$(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.

这篇关于使用的setTimeout控制轮询间隔jQuery的递归阿贾克斯调查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆