forTime循环内的SetTimeout [英] SetTimeout inside a for loop

查看:59
本文介绍了forTime循环内的SetTimeout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个可更改3张图像的z-index的脚本.基本上,脚本应以当前图片为目标,并在下一张图片上应用更高的Z索引,例如某种轮播,但具有Z索引而不是活动类.面临的挑战是在特定间隔后设置z-index.问题在于显示的是第一个图像,然后是最后一个.这是我的代码:

I'm trying to write a script that changes the z-index of 3 images. Basically the script should target the current image and apply a higher z-index on the next image, like a sort of carousel but with a z-index rather then active class. The challenge is to set the z-index after a specific interval. The problem is that the first image is displayed and then the last one. This is my code:

HTML:

<div class="changingimages">
    <img src="#" data-time="3000" width="100%" class="alternateimage alternateimage1">
    <img src="#" data-time="2000" width="100%" class="alternateimage alternateimage2">
    <img src="#" data-time="4000" width="100%" class="alternateimage alternateimage3">
</div>

jQuery脚本

<script type="text/javascript">

jQuery(document).ready(function(){

    var changeImg = function(i, time, currentImg) {

        setTimeout(function(){

            jQuery(currentImg).next().css("z-index", i);

        }, time);
    };

    var numberOfChilds = jQuery(".changingimages").children().length;
    var currentIndexClass;
    var currentImg;
    var time;

    for (var i=1; i<=numberOfChilds; i++) {

            currentIndexClass = '.alternateimage' + i;
            currentImg = jQuery(currentIndexClass);
            time = jQuery(currentIndexClass).attr("data-time");

            changeImg(i, time, currentImg);

    }

});

我认为循环中的闭包存在一些问题,但不确定!

I think there is some problem with the closure inside a loop, but not sure!

推荐答案

常见的误解是

It's a common misconception that setTimeout schedules events to run relative to previously queued events. It looks like you believe that, theoretically, the following:

setTimeout(f, 100);
setTimeout(g, 100);
setTimeout(h, 100);

将导致这样的时间轴:

0ms   Start
100ms Run f()
200ms Run g()
300ms Run h()

现实是, setTimeout 中的time选项表示至少在经过这么多时间后运行此函数".从前面的示例来看,您实际上会得到类似的东西

The reality is that the time option in setTimeout means "run this function after at least this much time has passed." Going off of the previous example, you would actually get something more like

0ms   Start
100ms Run f()
101ms Run g()
102ms Run h()

要正确分配代码空间,请继续增加超时时间,而不要替换超时时间.

To space out your code correctly, keep adding to the timeout time rather than replacing it.

var time = 0;

for (var i = 1; i <= numberOfChilds; i++) {
  currentIndexClass = '.alternateimage' + i;
  currentImg = jQuery(currentIndexClass);

  // Add to the previous time
  time += parseInt(jQuery(currentIndexClass).attr("data-time"), 10);
  changeImg(i, time, currentImg);
}

这篇关于forTime循环内的SetTimeout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆