title: JavaScript waiting until an image is fully loaded before continuing script
body: <p>I've been looking around a lot of JavaScript answers but I haven't found one that really answers my problem yet. What I'm trying to do is load an image, grab the pixel data, perform an analysis, and then load another image to repeat the process.</p>
  
  <p>My problem is that I can't preload all of the images because this script has to be able to work on large amounts of images and preloading could be too resource heavy. So I'm stuck trying to load a new image each time through a loop, but I'm stuck with a race condition between the image loading and the script drawing it to the canvas's context. At least I'm pretty sure that's what is happening because the script will work fine with the images precached (for example if I refresh after loading the page previously).</p>
  
  <p>As you'll see there are several lines of code commented out because I'm incredibly new to JavaScript and they weren't working the way I thought they would, but I didn't want to forget about them if I needed the functionality later.</p>
  
  <p>This is the snippet of code that I believe is giving rise to the problem:</p>
  
  <p>EDIT: So I got my function to work after following a suggestion</p>
  
  <pre><code> function myFunction(imageURLarray) {
    var canvas = document.getElementById('imagecanvas');
    console.log("Canvas Grabbed");
  
    if (!canvas || !canvas.getContext) {
      return;
    }
  
    var context = canvas.getContext('2d');
  
    if (!context || !context.putImageData) {
      return;
    }
  
    window.loadedImageCount = 0;
    loadImages(context, canvas.width, canvas.height, imageURLarray, 0);
  }
  
  function loadImages(context, width, height, imageURLarray, currentIndex) {
    if (imageURLarray.length == 0 || imageURLarray.length == currentIndex) {
      return false;
    }
    if (typeof currentIndex == 'undefined') {
      currentIndex = 0;
    }
  
    var currentimage = new Image();
    currentimage.src = imageURLarray[currentIndex];
  
    var tempindex = currentIndex;
    currentimage.onload = function(e) {
  
      // Function code here
  
      window.loadedImageCount++;
  
      if (loadedImageCount == imageURLarray.length) {
  
        // Function that happens after all images are loaded here
      }
    }
    currentIndex++;
    loadImages(context, width, height, imageURLarray, currentIndex);
    return;
  }
  </code></pre>