Marco Marco - 1 month ago 4
Javascript Question

Iterating for loop for set number of iterations each time it is called until the end of an array

I have a preload images function which I would like to use to preload 2 images each time it is called, until all the images are preloaded.
This is my function:

function preload() {
for (i; i < images.length; i++) {
images[i] = new Image()
images[i].src = '/imagecache/cover/' + images[i]
}
}




I am not sure how to achieve that, to be able to change start and number of iterations (2) each time it is called, until the whole array of images is preloaded?

Updated

This is my full script:

$(document).ready(function () {
var imagesIndex = 0;
var loadedImages = new Array();
var nextImage = 0;
preload();

function preload() {
for (i = 0; i < 2; i++) {
if (nextImage < images.length) {
var img = new Image();
img.src = '/imagecache/cover/' + images[nextImage];
loadedImages[nextImage] = img;
++nextImage;
}
}
}

$('#forward').click(function() {
imagesIndex++;
preload();

if (imagesIndex > (loadedImages.length - 1)) {
imagesIndex = 0;
}

$('#image').attr({"src" : '/imagecache/cover/' + loadedImages[imagesIndex], "alt" : name});
});

$('#back').click(function() {
imagesIndex--;

if (imagesIndex < 0) {
imagesIndex = (loadedImages.length - 1);
}

$('#image').attr({"src" : '/imagecache/cover/' + loadedImages[imagesIndex], "alt" : name});
});
});




Here I have forward and back functions on which I would like to call preload function to iterate 2 times.

Answer

Keep track of where you are in the array outside the function. But first, you have to fix the problem that you're overwriting what I assume is the URL of the image with the Image object before you grab that URL.

For instance:

var nextImage = 0;
function preload() {
    preload1();
    preload1();
}
function preload1() {
    if (nextImage < images.length) {
        var img = new Image();
        img.src = '/imagecache/cover/' + images[nextImage];
        images[nextImage] = img;
        ++nextImage;
    }
}

Of course, you could use a loop instead of preload1.