【问题标题】:How to slow down a loop with setTimeout or setInterval如何使用 setTimeout 或 setInterval 减慢循环速度
【发布时间】:2013-05-21 14:29:06
【问题描述】:

我有一个名为 RotatorNames 的数组。它包含随机的东西,但假设它包含["rotatorA","rotatorB","rotatorC"]

我想遍历数组,并且对于每个项目我想触发一个点击事件。我已经完成了一些工作,除了所有东西都会立即触发。如何强制循环在继续循环之前等待几秒钟。

这就是我所拥有的。

function Rotator() {
    var RotatorNames = ["rotatorA","rotatorB","rotatorC"];
    RotatorNames.forEach(function(entry){
        window.setTimeout(function() {
            //Trigger that elements button.
            var elemntBtn = $('#btn_' + entry);
            elemntBtn.trigger('click');
        }, 5000);
    });
}

你可以运行它来看看我的问题是什么。 http://jsfiddle.net/BxDtp/ 此外,有时警报会执行 A、C、B 而不是 A、B、C。

【问题讨论】:

    标签: javascript jquery foreach settimeout setinterval


    【解决方案1】:

    虽然我确信其他答案有效,但我更喜欢使用此设置:

    function rotator(arr) {
        var iterator = function (index) {
            if (index >= arr.length) {
                index = 0;
            }
            console.log(arr[index]);
            setTimeout(function () {
                iterator(++index);
            }, 1500);
        };
    
        iterator(0);
    };
    
    rotator(["rotatorA", "rotatorB", "rotatorC"]);
    

    演示: http://jsfiddle.net/BxDtp/4/

    对我来说,这似乎比通过将“正确”值传递给 setTimeout 来使迭代正确排列更合乎逻辑。

    这允许数组按顺序不断迭代。如果您希望它在通过一次后停止,请将index = 0; 更改为return;

    【讨论】:

    • 非常好,这实际上也重新循环。谢谢!
    【解决方案2】:

    可以根据当前索引增加超时时间:

    RotatorNames.forEach(function(entry, i) {
        window.setTimeout(function() {
            //Trigger that elements button.
            var elemntBtn = $('#btn_' + entry);
            elemntBtn.trigger('click');
        }, 5000 + (i * 1000)); // wait for 5 seconds + 1 more per element
    });
    

    【讨论】:

    • 这很好用,但由于某种原因,第一个数组项在到达 B 和 C 之前会重复
    • 我知道原因了。这是因为我从 0 开始 forloop,默认情况下已经显示了 0。
    【解决方案3】:

    试试:

    var idx = 0;
    function Rotator() {
        var RotatorNames = ["rotatorA", "rotatorB", "rotatorC"];
            setTimeout(function () {
                console.log(RotatorNames[idx]);
                idx = (idx<RotatorNames.length-1) ? idx+1:idx=0;
                Rotator();
            }, 5000);
    }
    Rotator();
    

    jsFiddle example

    (注意我用console.log而不是alert

    【讨论】:

      【解决方案4】:

      这样的事情应该做你所追求的:

      function Rotator(index){
        var RotatorNames = ["rotatorA","rotatorB","rotatorC"];
        index = (index === undefined ? 0 : index);
      
        var $btn = $("#btn_"+RotatorNames[index]);
        $btn.click();
      
        if(RotatorNames[index+1]!==undefined){
          window.setTimeout(function(){
            Rotator(index+1);
          }, 500);
        }
      }
      

      【讨论】:

        猜你喜欢
        • 2011-05-02
        • 2019-02-20
        • 2012-03-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-11
        • 2018-04-25
        相关资源
        最近更新 更多