Reputation: 3780
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
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