0

Is there a way to suspend jquery execution while waiting for requests to finish, so that you can track its progress? This is my code:

    $("span").click(function() {
        istrainning= true;
        for (var i=0;i<1000;i++)
            $.post("train.php",function(){
                $(".progressbar").width((i/10)+"%");
                $("label").html((i/10)+"%");
            });
    });

I want the statements

$(".progressbar").width((i/10)+"%");
$("label").html((i/10)+"%");

to execute only after finishing post request. please help.

--EDIT:

Sorry. It seems like my mistake is the 1000 requests being done all at the same time. is there a way to do it where all request will be done one at a time?

Ray
  • 31
  • 1
  • 5

3 Answers3

0

They are already inside the success callback so they already will execute after the POST is complete.

I believe your problem is that the loop is complete when the first ajax is done, and as such, i will always be 1000

Have a look at http://fixingthesejquery.com/#slide55

I don't think posting a 1000 HTTP requests is a particularly good idea, but to avoid the i scoping issue, you can use a closure:

$("span").click(function() {
    istrainning= true;
    for (var i=0;i<1000;i++) {
        $.post("train.php",(function(i){
            return function() {
                $(".progressbar").width((i/10)+"%");
                $("label").html((i/10)+"%");
            }
        })(i)); // supply i as a parameter to the IIFE
    }
});

Further reading

xec
  • 17,349
  • 3
  • 46
  • 54
  • this will not give a consistent result... assume what will happen if the 1st request finishes after the 500th request... the the value will change from `50%` to `.1%` – Arun P Johny Oct 03 '14 at 10:18
  • @ArunPJohny Yes, that's a good point. Since it's a progress bar the width should be increased instead of set to a calculation based on the iteration count. – xec Oct 03 '14 at 10:28
0

You could append .done(function() {....}) to your code to get something to run when successfully completed. .always() will run if successful or not.

jQuery.post( ) .done( ) and success:

Community
  • 1
  • 1
Mat Richardson
  • 3,576
  • 4
  • 31
  • 56
  • The second parameter to `$.post()` is the success callback (the same as `.done()`) – xec Oct 03 '14 at 10:14
0

The problem is the wrong use of closure variable in a loop.

$("span").click(function () {
    istrainning = true;
    var counter = 0,
        handler = function () {
            counter++;
            $(".progressbar").width((counter / 10) + "%");
            $("label").html((counter / 10) + "%");
        }
    for (var i = 0; i < 1000; i++) {
        $.post("/echo/html/", {
            html: '<b>' + i + '</b>'
        }, handler);
    }
});

Demo: Fiddle - simulates with only 5 loops

Note: Sending a 1000 ajax requests is never a good design, hopefully it is just done to test something

Community
  • 1
  • 1
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531