YMMD
YMMD

Reputation: 3780

Chaining Callback Functions through a Loop in Javascript

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/

Upvotes: 2

Views: 1172

Answers (2)

YMMD
YMMD

Reputation: 3780

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

Upvotes: 0

PSL
PSL

Reputation: 123739

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

Upvotes: 1

Related Questions