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