2

I don't want to preload my images at the same time anymore, I want to load them one after each other. Until now I did it like this:

for (var i = current; i < current + 5; i++) {
    images[i].load();
}

So I began to think how to use callbacks to load them sequentially: I can pass a callback to load(callback), which will be called after one image has been loaded. So I can also just do it like this and they will be loaded after each other:

images[current].load(function(){
    images[current + 1].load(function(){
        images[current + 2].load(function(){
            images[current + 3].load(function(){
                images[current + 4].load();
            });
        });
    });
});

This works, but I would love to transform it into a loop. I can't twist my head in a way to achieve this. Can you help?


I can only provide an example of my load(callback) method, because it is too long:

load = function(callback){
    // do preloading things and simulate load event:
    setTimeout(function(){
        callback.apply(this);
    }, 1000);
} 

Here's a fiddle to test it: http://jsfiddle.net/ajuc7g1q/1/

3
  • 1
    Post .load implementation. Commented Aug 17, 2014 at 5:28
  • Please .load implementation here as said above. Commented Aug 17, 2014 at 5:29
  • I posted an example of my load function and a fiddle to test it! Commented Aug 17, 2014 at 5:37

2 Answers 2

1

Probably a recursive function?

function loadImages(){
  var images = [img1, img2, ...];
  loadImage(images);

}

function loadImage(images){
  if(images.length){
      images.shift().load(function(){
          loadImage(images);
      });
  }
}

Demo

Sign up to request clarification or add additional context in comments.

2 Comments

Sorry, I forgot to mention that I don't always want to load all of the images, but only about five starting from a given index. Here is an example: jsfiddle.net/ajuc7g1q/1
Clean solution, but a minor technical point. This isn't recursive, as there is only onc instance of LoadImage on the stack at a time. Recursive specifically means there is something to return back to.
0

I just figured out how to do it recursively:

var call_chain = function(){};

for(var i = current + 5; i >= current; i--){
    (function(f, index){
        call_chain = function(){
            images[index].load(f);
        };
    })(call_chain, i);
}

call_chain();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.