Set a range in the execution of each for loop

Asked

Viewed 244 times

0

I am wanting to set an interval in the execution of each loop of 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 managing to do this?

4 answers

4

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

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>

  • 1

    I’m a typing slug :).

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>

Every 1 second the method loop which will check whether the variable’s value x is less than the amount of elements li in the document, if it is, returns in the console the text of that element.

2

In addition to the methods already mentioned, you can also use the operator await. This operator is used to "wait" 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>

1

Here I show a solution similar to @dvd but using let in the for that ends up capturing the right context not needing an extra function around the setTimeout. This is related to closures and with the scope of let just stay 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.