Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery AJAX with an interval

I have a question about an AJAX call within an interval. And why it doesn't work, or work the way it works.

I have this code (this one doesn't work)

setInterval($.ajax({
  //Place code here
}), 2000);

but then I make it this way

setInterval(function() {
  $.ajax({
    //Do ajax stuff here
  });
}, 2000);

Now it works, but to me this looks like I only make an extra anonymous function.

like image 655
Robbert Stevens Avatar asked Oct 01 '13 12:10

Robbert Stevens


1 Answers

setInterval requires a function or executable code in string format.

The first call will work when put within a string.

setInterval('$.ajax({ //Place code here })', 2000);

Using this syntax is discouraged for the same reasons as using eval.

setInterval can also take an optional list of params. You can take advantage of this fact and use something like this:

setInterval($.ajax/*a reference to the ajax function*/,
 2000, {url: 'someurl', success: onSuccess, error: onError}/*args passed to $.ajax*/
);

Note that this wouldn't work for object methods that use this to determine the context, as the value of this will be bound to window. That is, the following wouldn't work:

setTimeout($('h1').css, 1000, {'color': 'red'});
like image 143
c.P.u1 Avatar answered Oct 01 '22 16:10

c.P.u1