How to use setInterval or setTimeout with a for loop?

前端 未结 4 1853
清歌不尽
清歌不尽 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:57

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

提交回复
热议问题