【问题标题】:Javascript set up Timeout Functions within a for loopJavascript 在 for 循环中设置超时函数
【发布时间】:2015-01-17 12:53:19
【问题描述】:

我有一个循环选择对象并淡入该对象,但是当循环执行时,对象 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?

【问题讨论】:

标签: javascript jquery for-loop timing


【解决方案1】:

应该试试:

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

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

【讨论】:

  • 我会说将内部的id.fadeIn 修复为id_.fadeIn,它看起来已经准备好了;)
  • 我不敢相信事情就这么简单,谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-03
  • 2023-04-07
  • 2020-03-01
  • 1970-01-01
  • 2017-06-25
  • 1970-01-01
  • 2021-04-25
相关资源
最近更新 更多