How to use setInterval or setTimeout with a for loop?

家住魔仙堡 提交于 2019-12-01 22:58:37

let's suppose you're talking about elements of an array or a DOM collection

(function() {
   var arr = [...],
       len = arr.length;


   (function doProcess() {
       if (len--) {
           /* do something with arr[len] */
           setTimeout(doProcess, 20000);
       }
   })();    
})();

Edit: if you cannot reverse the array for any reason just use next version

(function() {
   var arr = [...],
       len = arr.length;


   (function doProcess(i) {
       if (i) {
            console.log(len - i);
           /* do something with arr[len - i] */
           setTimeout(function() { doProcess(--i); }, 20000);
       }
   })(len);    
})();

Here's some code I did for animating images using jQuery:

var enter = 500;
var show = 4000;
var exit = 300;
var direction1 = "right"; 
var direction2 = "left";
var logo = document.getElementById('Box1').getElementsByTagName('img');
var Num = $('#Box1 img').length;
var time_each = (enter+show+exit);
function startBox1(){
for(x=0;x<=Num-1;x++){
Box1(x);
}
}  
function Box1(x){
var buffer = time_each*x;
$(logo[x]).delay(buffer).show("slide", { direction: direction1 }, enter).delay(show).hide("slide", { direction: direction2 }, exit);
}
$(function(){
startBox1();
setInterval("startBox1()",(time_each)*Num);
});

The trick was to set a buffer which equaled the time it took for each animation by the index of the current animation. The FOR loop runs each code immediately; the .delay() action and the buffer variable makes it appear as if each animation was happening one after the other. Then setInterval() recalls the FOR loop after every animation is complete. It restarts the process continuously.

You have to define a function, and inside the function it needs to set a timeout on itself. Like this:

var els = [1, 2, 3, 4, 5];

((function process_els(el_index) {
  var el = els[el_index];

  // do stuff to el here
  console.log(el);
  // do stuff to el above

  if (el_index + 1 < els.length) {
    setTimeout(function() { process_els(el_index + 1); }, 20000);
  }
})(0);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!