How to make arrays go from one to one?

Asked

Viewed 62 times

0

I’m trying to get the website title here, always change its title from time to time but I don’t know how to do it. ignore the Alert it’s just for me to see how it looks

var titulo = [algum, valor, em, algum, lugar]

for (i = 0; i < 2; i++) {
    arraytitu[i] = setInterval(function () {
        if (i < 3) {
            alert(arraytitu);
            i++;
        } else {
            clearInterval(tmp[i])
        }
    }, 1000);
}```
  • in case, I can’t make go each value in the array, always goes all at once

1 answer

2

You don’t need a bow for. With only setInterval you already can. Just go through each index of the array to the end. When the variable value indice is equal to the size of the array, cancel the timer:

var titulo = ['tit1', 'tit2', 'tit3', 'tit4', 'tit5'];
var indice = 0;
var intervalo = setInterval(function () {
   if (indice < titulo.length) {
      console.log(titulo[indice]);
   } else {
      clearInterval(intervalo);
      console.log("Acabou!");
   }
   indice++;
}, 1000);

Edit

If you want an infinite loop in the array, you can do it this way:

var titulo = ['tit1', 'tit2', 'tit3', 'tit4', 'tit5'];
var indice = 0;
var intervalo = setInterval(function () {
   console.log(titulo[indice]);
   indice++;
   if (indice == titulo.length) indice = 0;
}, 1000);

  • 5

    Or to go around: console.log(titulo[indice % titulo.length]); (cutting the if/Else).

  • 3

    Remembering that depending on the interval and how long the user leaves the page open, indice will exceed the maximum limit of the integers. There are several ways to solve (including avoiding using the rest operation, rs), is as an exercise for those who choose to use :)

Browser other questions tagged

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