1

我有一个名为 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。

4

4 回答 4

6

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

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/

It just seems more logical to me than trying to get the iterations to line up correctly by passing the "correct" value to setTimeout.

This allows for the array to be continually iterated over, in order. If you want it to stop after going through it once, change index = 0; to return;.

于 2013-05-21T14:36:41.887 回答
3

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

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
});
于 2013-05-21T14:31:59.857 回答
0

Try:

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

(note that I used console.log instead of alert)

于 2013-05-21T14:36:49.460 回答
-1

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

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);
  }
}
于 2013-05-21T14:35:53.747 回答