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
Don’t try to pass
imto thesetTimeoutcallback. Your anonymous function can readim, as functions have access to their parent scope. If you try to pass it like that, it won’t work.setTimeoutwill call the callback internally, without passing any arguments. What you’re actually doing is creating a new, undefined, localimvariable inside the anonymous function, and blocking access to the variable from the outer scope. So this should work:However, your code is inside a loop, and just doing that inside the loop is not enough. Since the
setTimeoutcalls are asynchronous, when they’re executedimwill 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: