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

Sim*_*mon 6 javascript

我想要实现的是,最初将加载数据,然后使用相同的功能每十分钟更新一次.

考虑以下代码:

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);
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

useless setInterval call (missing quotes around argument?)
Run Code Online (Sandbox Code Playgroud)

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

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

谢谢.

Mat*_* H. 14

你需要使用:

setInterval(updateNamespace.update, 600000);
Run Code Online (Sandbox Code Playgroud)

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

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

setInterval(updateNamespace.update(), 600000);
Run Code Online (Sandbox Code Playgroud)

评估为

setInterval(undefined, 600000);
Run Code Online (Sandbox Code Playgroud)

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