Set a range in the execution of each loop of a for

0

I want to set a gap in the execution of each loop in my for

var li = document.getElementByTagName("li");
lengthLI = li.length;
for(var x = 0; x < lengthLI; x++){
    console.log(li[x].innerText);
    // setar intrvalo
}

How could I be able to do this?

    
asked by anonymous 04.03.2018 / 05:00

4 answers

4

You can use a auto-executed function with setTimeout inside the loop, which will simulate a delay in the for loop:

var li = document.getElementsByTagName("li"),
lengthLI = li.length;

for(var x = 0; x < lengthLI; x++){

   (function(x){
      setTimeout(function(){
         console.log(li[x].innerText);
      }, x*1000); // 1000 = 1 segundo
   }(x));

}
<ul>
   <li>li 1</li>
   <li>li 2</li>
   <li>li 3</li>
</ul>
    
04.03.2018 / 05:15
3

You can create a method and use setInterval , see:

let li = document.querySelectorAll('li');
let x = 0;
let intervalo = null;

const loop = () => {
  if (x < li.length) {
    console.log(li[x].innerText);
  } else {
    clearInterval(intervalo);
    console.log('Fim !');
    x = 0;
  }
  x++;
};

intervalo = setInterval(loop, 1000);
<li>Texto A</li>
<li>Texto B</li>
<li>Texto C</li>
<li>Texto D</li>
<li>Texto E</li>
<li>Texto F</li>
<li>Texto G</li>
<li>Texto H</li>
<li>Texto I</li>

The loop method will be executed every 1 second, which will check if the value of the x variable is less than the number of li elements in the document, if it returns the text of that element in the console

    
04.03.2018 / 05:16
2

In addition to the methods already mentioned, you can also use the await operator. This operator is used to "wait" for the result of a promise .

To use it, simply create an asynchronous function, for example:

const elements = document.querySelectorAll("li");

(async () => {for (let element of elements) {
  console.log( element )
  await new Promise( resolve => setTimeout(resolve, 1000) )
}})();
<li>Item 0</li>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
<li>Item 6</li>
<li>Item 7</li>
<li>Item 8</li>
<li>Item 9</li>
    
04.03.2018 / 08:03
1

Here I show a solution similar to that of @dvd but using let in for which ends up capturing the correct context and does not require an extra function around setTimeout . This is related to closures and the scope of let is only in the for .

Implementation:

const lis = document.getElementsByTagName("li");
for(let x = 0; x < lis.length; x++){
  setTimeout(() => console.log(lis[x].innerText), 1000 * x);
}
<li>Elemento 1</li>
<li>Elemento 2</li>
<li>Elemento 3</li>
    
04.03.2018 / 15:29