jQuery AJAX with an interval

Robbert Stevens

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.

c.P.u1

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章