Tony
Tony

Reputation: 12695

ASP.NET A problem with jQuery and a WebService's method

I invoke a WebService method asynchronously.

While the method is not complete, I use that jQuery code to update my progress bar (get progress value from that WebService)

   var intervalID = setInterval(updateProgress, 1000);

   function updateProgress() {

            $.ajax({
                type: "GET",
                url: "myPage.aspx/GetProgress",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async: true,
                success: function(msg) {
                    $("#result").text = msg.d;
                    var value = $("#progressbar").progressbar("option", "value");
                    if (value < 100) {
                        $("#progressbar").progressbar("value", msg.d);
                        $("#result").text(msg.d);
                    }
                    else {
                        clearInterval(intervalID);
                    }
                }
            });

The problem is, that the browser sends the requests (let's say 15 times) to get the progress value, but that requests are waiting while the asynchronous method is complete. Then, my server sends 15 times that value for the browser.

Why requests are waiting to complete the asynchronous method ??

Upvotes: 1

Views: 372

Answers (1)

Nick Craver
Nick Craver

Reputation: 630379

When you set async: true you're telling the requests to complete sequentially and lock the browser while doing so. If you want the UI to update, then you need to set a timeout instead of an interval, so the UI has time to update between requests, but it would be better to turn async off altogether and use setTimeout() instead, here's what I mean:

function updateProgress() {
    $.ajax({
        type: "GET",
        url: "myPage.aspx/GetProgress",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            $("#result").text = msg.d;
            var value = $("#progressbar").progressbar("option", "value");
            if (value < 100) {
                $("#progressbar").progressbar("value", msg.d);
                $("#result").text(msg.d);
            }
            else {
                setTimeout(updateProgress, 1000);
            }
        }
    });
}

This lets the request complete, doesn't lock up the browser or UI thread, and kicks off the next request when the first finishes, with a 1000ms delay, just adjust if needed. Otherwise say the user has 1200ms latency, currently you're queuing up requests that are overlapping...it's best not to use setInterval() in a repeated AJAX situation, since you don't know how long the request itself will take.

Upvotes: 1

Related Questions