Skip to content Skip to sidebar Skip to footer

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() {

Solution 1:

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.

Solution 2:

You can try something like this:

var imageList = ['1.png', '2.png', '3.png', '4.png', '5.png'];
var _images = imageList.slice(0);
varSTATIC_PATH = '/imagecache/cover/';

functionloadImage(image) {
  var img = newImage()
  img.src = STATIC_PATH + image;
  return img
}

functionloadNImages(n) {
  var tmp = _images.splice(0, (n || 1));
  return tmp.map(function(img) {
    returnloadImage(img);
  })
}

functioninitTimeout() {
  setTimeout(function() {
    var imgs = loadNImages(2);
    imgs.forEach(function(img){
      document.querySelector('.content').append(img)
    })
    if (_images.length > 0) {
      initTimeout();
    }
  }, 1000)
}
initTimeout()
<divclass="content"></div>

Post a Comment for "Iterating For Loop For Set Number Of Iterations Each Time It Is Called Until The End Of An Array"