AJAX间隔刷新? [英] AJAX Interval Refresh?

查看:81
本文介绍了AJAX间隔刷新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使AJAX函数更新约30秒.我已经完成了一个简单的版本,下面是代码.

I'm trying to make an AJAX function update about 30 seconds. I have a simple version of that done, here is the code.

var refInterval = window.setInterval('update()', 30000); // 30 seconds

var update = function() {
    $.ajax({
        type : 'POST',
        url : 'post.php',
        success : function(data){
            $('.voters').html(data);
        },
    });
};

这有效,但是,当函数被第一次调用时,我不希望它等待30秒,我只希望函数被调用,然后等待30秒,再次调用,等待30秒,再次调用,等等.有帮助吗?

This works, however, when the function is FIRST called I don't want it to wait 30 seconds, I just want the function to call, then wait 30 seconds, call again, wait 30 seconds, call again, etc. Any help?

推荐答案

考虑改用setTimeout-更可靠. setInterval计时器可以在窗口没有焦点时堆叠,然后在再次获得焦点时立即全部运行.使用setTimeout还可以确保如果第一个请求由于某种原因阻塞,则不会使多个AJAX请求排队.

Consider using setTimeout instead - it's more reliable. setInterval timers can stack when the window doesn't have focus and then all run at once when it gets focus back again. Using setTimeout also ensures that you don't get multiple AJAX requests queued up if the first one blocks for some reason.

要立即开始循环,请使用包裹在函数周围的IIFE(立即调用的函数表达式"):

To start the loop immediately, use an IIFE ("immediately invoked function expression") wrapped around the function:

(function update() {
    $.ajax({
        ...                        // pass existing options
    }).then(function() {           // on completion, restart
       setTimeout(update, 30000);  // function refers to itself
    });
})();                              // automatically invoke for first run

p.s.不要使用setIntervalsetTimeout的字符串参数-只需直接传递函数引用即可.

p.s. don't use string arguments to setInterval or setTimeout - just pass the function reference directly.

这篇关于AJAX间隔刷新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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