title: Delay between repeated AJAX call to a web method
body: <p>I have a ASP.Net web app with jquery implemented on the client side.  within a while loop, the client side jquery script makes an asynchronous call to a web method in the server side code.  The call returns the status of a long running server side task which jquery uses to update the user.  The goal is to have jquery repeatedly call the server until the status is complete, once done it breaks out of the while loop and notifies the user thatthe task is complete.</p>
  
  <p>My problem is that the below code runs in a while loop, but I want to make it delay or sleep between each call in order to prevent overwhelming the server with status requests.  I tried calling setTimeout in the code below, but it only works with the initial ajax call, every subsequent call occurs back to back.  Is there a way to efficiently delay each subsequent call to the server?  Is this the most efficient way to achieve the kind of behavior I'm describing?  Ideally I'd like a 2-5 second delay between each call.</p>
  
  <p>I have the following code</p>
  
  <p>Client Jquery:</p>
  
  <pre><code>var alertTimerId;
  $('input[name=btnStatus]').click(function () {
  
      var result  = false;
      //Loop while server reports task complete is true
      while (!result) {
        alertTimerId = setTimeout(function () {
          $.ajax({
            type: "POST",
            url: "Default.aspx/GetStatus",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: true,
            success: function (msg) {
              if(msg.d != false)
                result = msg.d;
            },
            error: function (xhr, ajaxOptions, thrownError) {
              alert('AJAX failure');
            }
          });
        }, 2000);
  
  
        if (count &gt; 0) {
          count--;
        }
      }
  
  
    });
  </code></pre>
  
  <p>Server Side ASP</p>
  
  <pre><code>[System.Web.Services.WebMethod]
          public static bool GetStatus()
          {
              return result;
          }
  </code></pre>