Javascript 在 for 循环中设置超时函数

Javascript set up Timeout Functions within a for loop

我有一个循环 select 和对象并淡入该对象,但是当循环执行时,对象 ID 停留在最后一个条目;

    var ordered = Array(elements.length);
            var x = 0;
            $('#' + that.options.slide_name + '_' + that.nextslide).children().each(function () {
                ordered[x] = $(this);
                $(this).fadeOut(1);
                $(this).attr('id','current_slide_content_' + x);
                x++;
            });
//fade each element
            var time = that.options.fade_speed / ordered.length
            var overlap = time / that.options.fade_step;
            //time = time + overlap;
            var wait = 0;
            var num = 0;
            var i = null;
            var funcs = Array(ordered.length);
            for(var a = 0; a < ordered.length; a++){
                var w = wait;
                var id = $('#current_slide_content_' + a);
                window.setTimeout( function (event) {
                    id.fadeIn(time);
                    console.log(id);
                },w);
                //$('#current_slide_content_' + a).fadeIn(time);  <-- on its own works, error is with the wait time
                wait = time + wait; 
            }

我将错误缩小到实际添加超时功能的最终循环中。

for(var a = 0; a < ordered.length; a++){
                var w = wait;
                var id = $('#current_slide_content_' + a);
                window.setTimeout( function (event) {
                    id.fadeIn(time);
                    console.log(id);
                },w);
                //$('#current_slide_content_' + a).fadeIn(time);  <-- on its own works, error is with the wait time
                wait = time + wait; 
            }

当元素的 id 被记录时,它应该是:

foo_0 foo_1 foo_2

但它显示为:

foo_2 foo_2 foo_2

我已经用了好几天并重新启动了好几次,我该如何为我的每个超时函数正确格式化 ID?

应该尝试:

window.setTimeout( (function(time_, id_){
    return function (event) {
        id_.fadeIn(time_);
        console.log(id_);
    }
})(time,id),w);

这是一个闭包,用于在函数范围内保存timeid的值