Zeno
Zeno

Reputation: 1829

jQuery hide() when JS loop finishes

I have this JS loop:

          for (var i = 0; i < jsArr.length; ++i) {
            $.post("checkdata.php", { names: jsArr[i], platforms: "1" })
            .done(function(data) {
                eval(data);
            });
          }

data is some jQuery CSS manipulation. I have a loading image that is under the "loadingImg" div class which is display on page load. checkdata.php checks the names against the API https://www.xboxleaders.com/

What's the best way to accomplish $('#loadingImg').hide(); (to hide the image) after the loop and the jQuery .done processes complete?

I have thought about adding it after the loop, but that does not guarantee checkdata has finished.

Upvotes: 0

Views: 136

Answers (4)

Jordan Denison
Jordan Denison

Reputation: 2727

One solution to this is by creating a second array that has the same number of elements as jsArr. On each .done, set the corresponding index of the second array to true. Then in each call of .done, check if all the values of the second array are true, and if so, hide. (Or you could just push a new value into the second array and check if the length of the arrays are the same for the hide to take effect)

doneChecks = [];
for (var i = 0; i < jsArr.length; ++i) {
    $.post("checkdata.php", { names: jsArr[i], platforms: "1" })
        .done(function(data) {
            doneChecks.push(true);
            eval(data);
            if (doneChecks.length == jsArr.length)
                $('#loadingImg').hide(); 
    });
}

Upvotes: 0

sabof
sabof

Reputation: 8192

$.when can be used to combine deferreds, and will resolve, when all of them are resolved.

var defs = [];
for (var i = 0; i < jsArr.length; ++i) {
  defs.unshift($.post("checkdata.php", { names: jsArr[i], platforms: "1" }));
  defs[0].done(function(data) {
    eval(data);
  });
}

$.when.apply($, defs).done(function() {
  $('#loadingImg').hide();
});

Upvotes: 3

Yevgen
Yevgen

Reputation: 1300

You better use waterfall

This question would be helpful.

Upvotes: 0

Joren Van Severen
Joren Van Severen

Reputation: 2349

Use a counter:

      var counter = 0;
      for (var i = 0; i < jsArr.length; ++i) {
        $.post("checkdata.php", { names: jsArr[i], platforms: "1" })
        .done(function(data) {
            counter++;
            eval(data);
            if(counter == jsArr.length){
                $('#loadingImg').hide();
            }
        });
      }

Upvotes: 1

Related Questions