简体   繁体   中英

using setTimeout in function that appends images

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 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 + "' />");
    };
}

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

    } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM