Continuing for loop only when image loads

107 views Asked by At
function readXML(){
    var xmlDoc = loadXML();
    var x = xmlDoc.getElementsByTagName("image");
    for (i = 0; i < x.length; i++) {
        if (i == 600){
            break;
        }
        var path = x[i].getElementsByTagName("path")[0].childNodes[0].nodeValue;
        var title = x[i].getAttribute("class");
        this.imageArray.push(new InfoImage(path,title));
        while(this.imageArray[i].isImageLoaded() == false); //something like this
        console.log(this.imageArray[i].getMaxPixels());

    }
}

function InfoImage(path,title){
    this.path = path;
    this.title = title;
    this.color = undefined;
    this.maxPixels = undefined;
    this.imageLoaded = false;

    this.init = function(){
        var canvas = document.querySelector("canvas");
        var img_Color = new Image_Processing_Color(canvas);
        var img = new Image();
        var info_image = this;
        img.onload = function () {
            img_Color.init(img);
            info_image.color = img_Color.getDominantColor();
            info_image.maxPixels = img_Color.getDominantColorPixels();
            info_image.imageLoaded = true;
        };
        img.src = path;
    };

    this.isImageLoaded = function(){
        return this.imageLoaded;
    }

    this.getPath = function(){
        return this.path;
    };

    this.getTitle = function(){
        return this.title;
    };

    this.getColor = function(){
        return this.color;
    };

    this.getMaxPixels = function(){
        return this.maxPixels;
    };

    this.init();
}

I want my for loop to only continue to the next iteration when img.onLoad completes. The while i'm using blocks the code and doesn't let img.onLoad complete. Is there a way to do this? Without changing the code structure.

2

There are 2 answers

0
Vince Verhoeven On BEST ANSWER

You can check the .complete property of an img:

var x = document.getElementById("myImg").complete; the result can be true or false

0
idoberko2 On

If I understood you correctly, I believe your best option is to use async.parallel (if you want it to be serial, they have a function for it - series).

This function can perform a series of tasks for you and issue a callback on complete (in which you get informed of errors).