0

This question is related to this: jQuery recursive ajax poll using setTimeout to control the poll interval, but slightly different and I cannot figure out why.

function _poll(n) {
  $.ajax({
    url: "/check_status",
    type: "POST",
    data: {state: 0},
    success: function(xhr) {
       var data = $.parseJSON(xhr)
       if (data.status == 0) {
         poll(n)
       }
    }
  });
}

function poll(n) {
  setTimeout(_poll(n), 5000);
}

Like the other question, the request is also sent out crazy. Thanks a lot for the help!

Note, I have to use different names "poll" and "_poll" for other purposes.

Community
  • 1
  • 1
user180574
  • 5,681
  • 13
  • 53
  • 94

1 Answers1

1

I believe your problem is on this line:

setTimeout(_poll(n), 5000);

You're invoking the function and passing its return value, you have to pass it in as an argument. E.g. think about how this code would execute:

setTimeout(Math.Sum(2, 7), 5000);

It would return 9 as the first variable, not the function itself.

The easiest way to fix this is to use this format instead, which defines an anonymous function:

setTimeout(function(){ _poll(n) }, 5000);
James G.
  • 2,852
  • 3
  • 28
  • 52