Suppose I have the following code to preload 2 images, and do something only after both images have loaded:
var numLoaded = 0;
function OnImageLoaded()
{
numLoaded++;
if (numLoaded==2) alert("Got 'em!");
}
var a = new Image();
var b = new Image();
a.onload = OnImageLoaded;
b.onload = OnImageLoaded;
a.src = 'foo.jpg';
b.src = 'bar.jpg';
Assigning a.src
and b.src
causes both images to be loaded in the background, and OnImageLoaded()
being called then they're ready.
Obviously the code after if (numLoaded==2)
is supposed to run only once.
Now, is there a possibility of this happening:
- the first image is loaded, the function gets called,
numLoaded++
increases the counter to one, - the second image is loaded, the function gets called (in a diffrent thread),
numLoaded++
increases the counter to two, - the first thread checks
numLoaded==2
which is now true, so the code gets executed, - the second thread also checks
numLoaded==2
which is still true, so the supposed-to-run-once code gets executed again ← problem!
Is this a chance (albeit very small) and how do I avoid this? In other languages I'd use a Critical Section for this, or a mutex, or make numLoaded volatile and do n=(++numLoaded)
or something, but how do I go about this in JS?