1

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:

  1. the first image is loaded, the function gets called, numLoaded++ increases the counter to one,
  2. the second image is loaded, the function gets called (in a diffrent thread), numLoaded++ increases the counter to two,
  3. the first thread checks numLoaded==2 which is now true, so the code gets executed,
  4. 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?

RocketNuts
  • 9,958
  • 11
  • 47
  • 88
  • JavaScript is single threaded. For this you could use promises, for example `Promise.all([img1, img2]).then(onLoaded)` – elclanrs Sep 14 '15 at 22:01

1 Answers1

4

Javascript does not run concurrently under normal circumstances. There are ways of doing so using Node.js but it's rather difficult and not something you have to worry about for typical situations.

Community
  • 1
  • 1
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91