javascript - 匿名javascript轮询函数不会立即触发setTimeout ajax调用

标签 javascript ajax settimeout anonymous-function polling

我有一个匿名轮询函数,它有一个 setTimeout 来每 30 秒启动一次 ajax 调用。然而,匿名函数确实会立即启动,但由于某种原因,ajax 调用不会立即启动,而是仅在 30 秒后启动。我是否错过了诸如立即调用它以立即触发之类的东西?

(function poll() {
        console.log('polling called');
        setTimeout(function () {
            $.ajax({
                url: "/server/call",
                type: 'GET',
                dataType: "json", 
                timeout: 30000,
                success: function (data) {
                    var currentdate = new Date();
                    var datetime = "Last Sync: " +                  currentdate.getDate() + "/" + (currentdate.getMonth() + 1) + "/"
                    + currentdate.getFullYear() + " @ "
                    + currentdate.getHours() + ":"
                    + currentdate.getMinutes() + ":"
                    + currentdate.getSeconds();

                    console.log(datetime);
                    console.log('call was successful at: ' + datetime);
                }
            });
        },
        30000);
    })();

日志记录仅在 30 秒后开始,而不是立即开始。 谢谢

最佳答案

如果您正在编写一些轮询函数,则必须在上一个函数完成后发送请求。服务器必须在几秒钟后响应浏览器。此时服务器处理所有其他请求。这是示例:

(function poll() {
            console.log('polling called');

            $.ajax({
                url: "/server/call",
                type: 'GET',
                dataType: "json",
                timeout: 30000,
                success: function (data) {
                    var currentdate = new Date();
                    var datetime = "Last Sync: " + currentdate.getDate() + "/" + (currentdate.getMonth() + 1) + "/"
                        + currentdate.getFullYear() + " @ "
                        + currentdate.getHours() + ":"
                        + currentdate.getMinutes() + ":"
                        + currentdate.getSeconds();

                    console.log(datetime);
                    console.log('call was successful at: ' + datetime);
                },
                complete: function () {
                    setTimeout(function () {
                        poll()
                    }, 200) //do nothing 200ms
                }
            });
        })();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

关于javascript - 匿名javascript轮询函数不会立即触发setTimeout ajax调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43072497/

相关文章:

javascript - 转换javascript中的日期格式

javascript - 删除正则表达式中不必要的括号

javascript - 如果ajax成功则关闭对话框

php - 在 WooCommerce 购物车页面中添加费用的自定义复选框

javascript - 使用 jquery 重新启动无限循环时,Ticker 文本跳转

javascript - 是否可以使用 Jquery 在 HTML 中添加文本或 html 标签?

javascript - 使用setTimeout逐字符打印字符串

javascript - JavaScript 中的事件循环如何工作? process.nextTick 和 setImmediate 如何工作?

javascript - jQuery 在移动设备上不显示图像

javascript - Mouseenter 和 mouseleave - 在触发功能前稍等片刻?