I’m trying to test if urls dynamically passed to image tags would resolve or not. I’m using the following javascript function:
testImageUri = function(src) {
var img = new Image();
var imgStatus = false;
var goodUri = function() {
imgStatus = true;
};
var badUri = function() {
imgStatus = false;
};
img.onload = goodUri;
img.onerror = badUri;
img.src = src;
return imgStatus;
}
The functions badUri and goodUri get called as expected, but they appear to be “late” as the testImageUri function seems to return before they get to change the imgStatus variable.
How do one resolve such problems in javascript?
How do one avoid them?
is there a rule of thumb to recognize situations susceptible to create this?
EDIT
Thanks all for your replies. I think I understand what’s going on now. I will be implementing the function as described in the first reply, but with an additional parameter for the callback as suggested.
Thanks again.
By setting the img.onload and img.onerror, you attach functions to these event handlers. The script will attach them, and when succesful, execute the remainder of the script.
As you’ve already noticed, Javascript does not halt execution until these events actually fire.
Instead of returning the imgStatus (which will probably be used by a new function, which I’ll reference to as
doSomething), consider adding thisdoSomethingfunction to the event handlers themselves, making it act as a callback function: