Implementing background loading properly and efficiently
<p>The following code is a summary of what I'm trying to do, which is to develop a interface that allows the user to scroll left and right through images. Images start off the screen and then to the centre, and it also pushes the previous image back off the screen.</p>

<p>I would love some advice on the code I have or suggestions on how to do it better. Obviously, if the user rapidly clicks the arrows it will undoubtedly break the script, so I will need help here. Maybe prevent the arrows from being clicked when in a "load" state?</p>

<p>I should also mention that backgroundLoad preloads the next and previous image. And when I say "off screen" it will animate to the centre. I'm not looking for a image gallery/lightbox solution. This question is more about the preloading process.</p>

<pre><code>var imgArray=[];
    var b = 0;

    function loadImage(ini){
        b = ini;

        //preload image
        var num_loaded = 0;
    imgArray[ini] = new Array();;



    for(var i=0;i&lt;2;i++){
        imgArray[ini][i] = new Image();

        imgArray[ini][i].onload = function(){
            num_loaded++;

            if(num_loaded == 1){

            }

            if(num_loaded == 2){
                //do something




               backgroundLoad(ini+1);



            }

        }

        imgArray[ini][i].src = ArrayOfFiles[ini][i];

    }


}

function backgroundLoad(ini){
    var num_loaded = 0;
    imgArray[ini] = new Array();;

    for(var i=0;i&lt;2;i++){
        imgArray[ini][i] = new Image();

        imgArray[ini][i].onload = function(){
            num_loaded++;


            if(num_loaded == 2){



                // loaded




            }

        }

        imgArray[ini][i].src = ArrayOfFiles[ini][i];

    }


}

$("div#arrow-left").click(function(){

    loadImage(b+1);
});

$("div#arrow-right").click(function(){

    loadImage(b-1);
});
</code></pre>
