开发者

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, pleas开发者_JAVA技巧e 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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜