javascript - How to slow down a loop with setTimeout or setInterval -
i have array called rotatornames. contains random things let's contains ["rotatora","rotatorb","rotatorc"]
.
i want loop through array, , each item want trigger click event. have got of working, except get's triggered instantly. how can force loop wait few seconds before continues looping.
here's have.
function rotator() { var rotatornames = ["rotatora","rotatorb","rotatorc"]; rotatornames.foreach(function(entry){ window.settimeout(function() { //trigger elements button. var elemntbtn = $('#btn_' + entry); elemntbtn.trigger('click'); }, 5000); }); }
you can run see issue is. http://jsfiddle.net/bxdtp/ also, alerts a,c,b instead of a,b,c.
while i'm sure other answers work, prefer using setup:
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"]);
demo: http://jsfiddle.net/bxdtp/4/
it seems more logical me trying iterations line correctly passing "correct" value settimeout
.
this allows array continually iterated over, in order. if want stop after going through once, change index = 0;
return;
.
Comments
Post a Comment