I have the following problem. I've created a class in whose constructor I'm loading a couple of images and I need to delay the remaining initializations until they are completely loaded. The code I used is as follows (an excerpt from the constructor):
var self = this;
var imagesToLoad = 4;
var finishInit = function() {
alert(imagesToLoad);
imagesToLoad--;
if (imagesToLoad == 0) {
// remaining initializations
}
}
this._prevIcon = new Image();
this._prevIcon.onload = finishInit;
this._prevIcon.src = "img1.png";
this._nextIcon = new Image();
this._nextIcon.onload = finishInit;
this._nextIcon.src = "img2.png";
this._pauseIcon = new Image();
this._pauseIcon.onload = finishInit;
this._pauseIcon.src = "img3.png";
this._playIcon = new Image();
this._playIcon.onload = finishInit;
this._playIcon.src = "img4.png";
To my surprise, when executed the displayed dialogs read 4,4,4,4 in Firefox 7 and 4,3,2,4 in IE 9. I'm confused becaused I believed that JS is single-threaded and thus one event handler should not interrupt another. Where's the catch (or my mistake)?
Thanks in advance. Best regards, Tomek