Delay between repeated AJAX calls to web method

I have an ASP.Net web application with jquery implemented on the client side. in a while loop, the client-side jQuery script makes an asynchronous call to the web method in the server-side code. The call returns the status of a long running server side task that jquery uses to update the user. The goal is for jquery to repeatedly call the server until the status is complete, once it finishes the while loop and notifies the user that the task has completed.

My problem is that the code below works in a while loop, but I want to make it delay or sleep between each call to prevent the server from being overwhelmed by status requests. I tried calling setTimeout in the code below, but it only works with the initial ajax call, every subsequent call happens back. Is there a way to effectively defer each subsequent call to the server? Is this the most efficient way to achieve this behavior that I am describing? Ideally I would like to delay 2-5 seconds between each call.

I have the following code

JQuery client:

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 > 0) {
        count--;
      }
    }


  });

      

Server ASP

[System.Web.Services.WebMethod]
        public static bool GetStatus()
        {
            return result;
        }

      

+1


source to share


2 answers


How about something like the following? The idea is that the Ajax call is encapsulated into a function, doAjax()

and then from the Ajax success handler, if the result is false, you use it setTimeout()

to queue the next call doAjax

, otherwise you perform whatever action you want to get the true result. (You can also call doAjax()

from an Ajax error handler.)

$('input[name=btnStatus]').click(function () {

    function doAjax() {
       $.ajax({
          type: "POST",
          url: "Default.aspx/GetStatus",
          data: "{}",
          contentType: "application/json; charset=utf-8",
          dataType: "json",
          async: true,
          success: function (msg) {
             if (!msg.d)
                 setTimeout(doAjax, 2000);
             else {
                 // Success! Notify user here
             }
          },
          error: function (xhr, ajaxOptions, thrownError) {
            alert('AJAX failure');
          }
       });
    }

    doAjax();

});

      



(Note: I removed the if statement with using count

as it doesn't seem to be relevant to the question. If your real code uses it, it just updates it in the Ajax success handler.)

+5


source


Underscore.Js has a helper function .throttle()

:

throttle_.throttle (function, wait)

Creates and returns a new, throttling version of the passed function that, when called repeatedly, will actually only call the original function at most once every milliseconds of waiting. Useful for speed limit events that happen faster than you can keep up.



var throttled = _.throttle(updatePosition, 100);
$(window).scroll(throttled);

      

0


source







All Articles