Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

123
Visualizações
How do i get rid of undefined in an array?

I am a self taught newbie at programming and I'm trying to play around with arrays, DOM and setInterval() method. I wrote a code that accesses the h1 tag of my html file and displays each element of an array at 1000 millisecond intervals in that tag. Unfortunately, the code runs successfully but displays "undefined" at the end of the execution. When I check the elements section of the Chrome Dev Tools, I realize that my h1 tag keeps blinking which I assume stipulates that my code keeps running even after all the elements in the array have been extinguished. I have used the filter method, clearTimeout() method and still get the same results. I will paste my code below. Hopefully I get a solution to my issue. Appreciate the feedback in advance!

function myFunction() {
  const welcome = ["Hello", "My", "Name", "Is", "Philip", "Nice", "To", "Meet", "You!"];

  for (let i = 0; i < welcome.length; i++) {
    function subset() {
      document.getElementById("heading").innerHTML = welcome[i++];
    }
    setInterval(subset, 1000);
    return;
  }
}
myFunction();
<h1 id="heading"></h1>

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You could reorganize this so that each function call sets up the next function call. This way you don't need to worry about keeping track of intervals to clear and it's easier to understand how i is being incremented. If you're not clear on how function.bind() works I recommend reading up on that, it's pretty useful.

function myFunction(i) {
const welcome = ["Hello", "My", "Name", "Is", "Philip", "Nice", "To", "Meet", "You!"];
document.getElementById("heading").innerHTML = welcome[i];
if (i < welcome.length - 1)
    setTimeout(myFunction.bind(null, i + 1), 1000);

} myFunction(0);

about 4 years ago · Juan Pablo Isaza Relatório

0

I think the problem is you use setinterval which is endlessly running every 1000s unless you reset it or an error stops it - it's not bound to your loop. This comes quite near to what you did:

    let cnt = 0;
    const welcome = ["Hello", "My", "Name", "Is", "Philip", "Nice", "To", "Meet", "You!"];
    const headingTag = document.getElementById("heading");

    function headingLoop() {
        setTimeout(function() {
            headingTag.innerHTML = welcome[cnt];
            cnt += 1;
            if (cnt < welcome.length) {
                headingLoop();
            }
        }, 1000);
    }

    headingLoop(); 
about 4 years ago · Juan Pablo Isaza Relatório

0

In sticking with your current setInterval() approach, you could do something like this.

This approach eliminates the need for the loop. Because setInterval() is calling the function repeatedly, it is taking care of that.

// set array
const welcome = ["Hello", "My", "Name", "Is", "Philip", "Nice", "To", "Meet", "You!"];

// declare index tracking variable and set to 0
let i = 0;

// declare your setInterval function and assign to myInterval so you can clear later
const myInterval = setInterval(myTimer, 1000);

// declare the function that setInterval() will call to output the array to the document
function myTimer() {
  document.getElementById("heading").innerHTML = welcome[i];
  i++;

  // clear interval when you've reached the end of the array
  if(i > welcome.length - 1) {
    clearInterval(myInterval);
  }
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda