How to use setInterval or setTimeout with a for loop?

前端 未结 4 1888
清歌不尽
清歌不尽 2021-01-21 22:28

I am trying to set an interval when some code runs but only need to do it based on the number of elements there are. Here\'s a quick example:

5 total elements

Ru

4条回答
  •  渐次进展
    2021-01-21 22:38

    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);
    

提交回复
热议问题