For loop wait: jquery

91 Views Asked by At
    for (var i in ids) {
       alert("image" + i + ".png");
       setTimeout(function () {
           (function () {
               fs.root.getFile("image" + i + ".png", {
                   create: true
               }, function (fileEntry) {
                   alert("fileimage" + i + ".png");
                   console.log(fileEntry);
                   fileEntry.createWriter(function (fileWriter) {

                       fileWriter.onwriteend = function (e) {
                           console.log("image successfully written to filesystem.");

                       };

                       var blob = new Blob([ids[i]]);
                       fileWriter.write(blob);
                   }, errorHandler);
               }, errorHandler);
           })(i)
       }, i * 1000);

   }

I am trying to save multiple images to file api. ids array has multiple images as blobs. Here my problem is that, 1st alert ie,"alert("image"+i+".png");" gets triggered 4 times and then only 2nd alert is getting triggered for the first time. How can i make it get triggered one after the other??

Please help, Thanks

2

There are 2 best solutions below

0
On

setTimeout doesn't stop the execution and wait for the function to complete. It returns immediately. The function passed to it is then called after defined milliseconds.

0
On
for (var i in ids) {
   alert("image" + i + ".png");

This triggers your 4 alerts one after another because it is in the loop and it does not care whether images are load or not.

2nd alert seems to be triggered when fs.root.getFile ends and callback is fired.

You could experiment with following

for (var i in ids) {
   setTimeout(function () {
       // alert("image" + i + ".png"); // here will be delayed also
       (function () {
           alert("image" + i + ".png");
           fs.root.getFile("image" + i + ".png", {