在JavaScript中使用setInterval而不使用内联的匿名函数

前端之家收集整理的这篇文章主要介绍了在JavaScript中使用setInterval而不使用内联的匿名函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想要实现的是,最初将加载数据,然后使用相同的功能每十分钟更新一次.

考虑以下代码

var updateNamespace = (function() {
    var object = '#updates',load = 'loader';

    return {
        update: function() {
            $(object).addClass(load).load('update.PHP',function(reponse,status,xhr) {
                if (status == 'error') {
                    $(this).html('<li>Sorry but there was an error in loading the news &amp; updates.</li>');
                }
                $(this).removeClass(load);
            }); 
        }
    }
})();

setInterval(updateNamespace.update(),600000);

我收到此错误

useless setInterval call (missing quotes around argument?)

我怎样才能解决这个问题?

写这个或使用setInterval函数有什么更好,更优雅的方法

谢谢.

解决方法

你需要使用:
setInterval(updateNamespace.update,600000);

(注意删除的invocation()运算符.)

您编写的代码调用setInterval时实际上会调用updateNamespace.update.因此,

setInterval(updateNamespace.update(),600000);

评估为

setInterval(undefined,600000);

您希望将setInterval传递给函数,而不是调用它的结果.

原文链接:https://www.f2er.com/js/150269.html

猜你在找的JavaScript相关文章