Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using setInterval in JavaScript without using an inline, anonymous function

Tags:

javascript

What I'm trying to achieve is that initially data will be loaded and then be updated every ten minutes using the same function.

Consider this code:

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);

I get this error:

useless setInterval call (missing quotes around argument?)

How can I fix this?

What's a better and more elegant way of writing this or using the setInterval function?

Thanks.

like image 395
Simon Avatar asked Feb 07 '12 05:02

Simon


1 Answers

You need to use:

setInterval(updateNamespace.update, 600000);

(Note the removed invocation() operator.)

Your code, as written, will actually invoke updateNamespace.update when you call setInterval. Hence,

setInterval(updateNamespace.update(), 600000);

evaluates to

setInterval(undefined, 600000);

You want to pass setInterval a REFERENCE to your function, not the result of its invocation.

like image 149
Matt H. Avatar answered Oct 22 '22 23:10

Matt H.