Using setInterval in JavaScript without using the built-in anonymous function

I am trying to ensure that the original data is downloaded and then 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 is the best and elegant way to write or use the setInterval function?

Thanks.

+6
source share
3 answers

You need to use:

 setInterval(updateNamespace.update, 600000); 

(Note the remote call ().)

Your code, as written, will call updateNamespace.update when calling setInterval. Consequently,

 setInterval(updateNamespace.update(), 600000); 

estimated as

 setInterval(undefined, 600000); 

You want to pass setInterval reference to your function, not the result of calling it.

+14
source

For some reason, JavaScript wants to see quotes around the method of your call. As if it were a string. Not sure why this is so. Matt H. said that if you pass a link that will fix the problem. But this will not work if you need to pass an argument. So I don’t know, maybe JavaScript just saves the method as a string and then hides it to its normal value when it is used.

0
source

try setInterval('updateNamespace.update()', 600000);

Pay attention to the quotes around the function call.

-6
source

Source: https://habr.com/ru/post/907819/


All Articles