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.
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'});
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With