Reputation: 23181
I'm having trouble using this append()
function in a setTimeout
. If I remove the SetTimeout, then all of the images load. Once I put it in here, it seems like the variables become out of scope or invalid. Any suggestions as to what I'm doing wrong here?
// thumbs[] is an array with image sources.
for (var imageIndex = 0; imageIndex < thumbs.length; imageIndex++) {
var im = thumbs[imageIndex];
setTimeout(function(im){
$("#a").append("<img class='images' src='" + im + "' />");
},1000);
} // end for
Upvotes: 1
Views: 1205
Reputation: 23208
Try this. In your case im
inside setTimeout
is undefiend
.
for (var imageIndex = 0; imageIndex < thumbs.length; imageIndex++) {
var im = thumbs[imageIndex];
setTimeout(function(im){
$("#a").append("<img class='image' src='" + im + "' />");
},1000, im);
}
IE dont support passing parameter in setTimeout
Try this if you want it to work across all browsers
for (var imageIndex = 0; imageIndex < thumbs.length; imageIndex++) {
var im = thumbs[imageIndex];
(function(im){
setTimeout(function(){
$("#a").append("<img class='image' src='" + im + "' />");
},1000);
})(im);
}
Upvotes: 5
Reputation: 71918
Don't try to pass im
to the setTimeout
callback. Your anonymous function can read im
, as functions have access to their parent scope. If you try to pass it like that, it won't work. setTimeout
will call the callback internally, without passing any arguments. What you're actually doing is creating a new, undefined, local im
variable inside the anonymous function, and blocking access to the variable from the outer scope. So this should work:
var im = thumbs[imageIndex];
setTimeout(function(){
$("#a").append("<img class='images' src='" + im + "' />");
},1000);
However, your code is inside a loop, and just doing that inside the loop is not enough. Since the setTimeout
calls are asynchronous, when they're executed im
will be the last value from your loop (thumbs.length
), always. You can avoid that by creating a closure. Sushil's answer is an example of that, so I'll show you another style:
for (var imageIndex = 0; imageIndex < thumbs.length; imageIndex++) {
var im = thumbs[imageIndex];
setTimeout(createTimerCallback(im), 1000);
}
function createTimerCallback(im) {
return function(){
$("#a").append("<img class='images' src='" + im + "' />");
};
}
Upvotes: 6