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

141
Visualizações
how not to flood the html page with the innerhtml

I have this code :

function addInDiv() {
    let div = document.getElementById("divName");
    div.innerHTML += '<p>' + "test" + '</p>'   
}
    
setInterval(addInDiv, 1000); 

this code make

<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>

... infinitely and flood the computer CPU.

I would like "divName" to only contain the last 5 lines that have been added by div.innerHTML

so, how can i display the last 5 lines displayed so as not to flood the html page and the pc's cpu

thanks

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

0

Store the number of appended elements in a variable, increment it every time you append, and check whether its been appended 5 times or not. If it has, cancel the interval.

var appended = 0;
var interval

function addInDiv() {
  if (++appended == 6) {
    clearInterval(interval)
  }
  let div = document.getElementById("divName");
  div.innerHTML += '<p>' + "test" + '</p>'
}

interval = setInterval(addInDiv, 1000);
<div id="divName"></div>

about 4 years ago · Juan Pablo Isaza Relatório

0

With jQuery:

var counter = 0;
function addInDiv() {
    counter++
    if(counter <= 5) {
        $('#divName').append('<p>' + "test" + '</p>');
    }       
}
    
setInterval(addInDiv, 1000); 
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