简体   繁体   中英

setTimeout() won't trigger the function

I'm trying to trigger the function in 5ooo second again and again with first_pic variable that contains different integer. Every time this function runs it adds plus 1 to first_pic variable, apparently it won't work, please help.

function slide(){
    var total_pic = $("#slide_show").children().length;
    var first_pic = $("#slide_show li:first-child").css('z-index',total_pic).index()+1;
    $("#slide_show li:nth-child("+first_pic+")").fadeOut(4000, function(){
        first_pic = first_pic + 1;
    });
    setTimeout(slide, 5000);
};
slide();

variable adds 1 nicely, but setTimeout doesn't trigger function again

Your first_pic is a local variable within the slide function. That means that each time you call slide , you get a new first_pic variable. Your fadeOut callback will update the first_pic that it is a closure for but the slide called by setTimeout will get its own first_pic . If you want to use the same first_pic for every execution of slide you will have to make it global or make its value persistent with data or a cookie.

Have a look at this, it might clarify that's going on:

function slide() {
    var first_pic = 5;
    $('#fade').fadeOut(1000, function() {
        first_pic = first_pic + 1;
        $('#fade').show();
        $('#out').text(first_pic);
    });
    setTimeout(slide, 2000);
};
slide();

Live version (with HTML): http://jsfiddle.net/ambiguous/PRaLH/

And compare it to how this behaves:

var first_pic = 5;
function slide() {
    $('#fade').fadeOut(1000, function() {
        first_pic = first_pic + 1;
        $('#fade').show();
        $('#out').text(first_pic);
    });
    setTimeout(slide, 2000);
};
slide();

Live version: http://jsfiddle.net/ambiguous/Ntqjh/

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