简体   繁体   中英

setTimeout not adding a delay

This is my code:

function transition(index){
    $("#right-panel").find("img").each(function(){
        if ($(this).index() === index){
            setTimeout(function(){
                $(this).fadeIn(750);
            }, 100000000);
        }else{
            $(this).fadeOut(750);
        }
    });
}

For some reason, the setTimeout in the function is not causing a delay for the fadeIn. What am I doing wrong?

this in the setTimeout callback isn't the same as outside it.

var self = this;
setTimeout(function(){
    $(self).fadeIn(750);
}, 100000000);

Although you could just use .delay() .

$(this).delay(100000000).fadeIn(750)

Overall a better approach would seem to be to use .eq() to grab the one you want to .fadeIn() , and .fadeOut() the rest.

function transition(index){
    var images = $("#right-panel").find("img");// get all the images
    var fadein = images.eq(index)
                       .delay(100000000)
                       .fadeIn(750); // fadeIn the one at "index"
    images.not(fadein).fadeOut(750); // fadeOut all the others
}

Why do you need setTimeout at all?

function transition(index){
    $("#right-panel").find("img").each(function(){
        if ($(this).index() === index){ // did you check this statement?
            $(this).delay(100000000).fadeIn(750);
        }else{
            $(this).fadeOut(750);
        }
    });
}

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