ipi*_*xel 1 javascript foreach jquery settimeout setinterval
我有一个名为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);
});
}
Run Code Online (Sandbox Code Playgroud)
你可以运行它来查看我的问题.http://jsfiddle.net/BxDtp/ 此外,有时警报会执行A,C,B而不是A,B,C.
虽然我确定其他答案有效,但我更喜欢使用此设置:
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"]);
Run Code Online (Sandbox Code Playgroud)
演示: http ://jsfiddle.net/BxDtp/4/
对我来说,似乎比通过传递"正确"值来使迭代正确排列更合乎逻辑setTimeout.
这允许按顺序连续迭代数组.如果您希望它在完成一次后停止,请更改index = 0;为return;.
| 归档时间: |
|
| 查看次数: |
4377 次 |
| 最近记录: |