Cross Cross - 2 months ago 17
Javascript Question

How append in jquery in for loop with setInterval without getting an infinite loop

I am making a listing system that updates checking new data from a json file every 3 seconds by appending the response.list[i].firstname to document.getElementById("list"). but i am getting unlimited loop.

output:

name1

name2

name1

name2

name1

name2

(to infinity..)

<script>
list();
setInterval(list, 3000);
function list() {
$.getJSON('list.php',function(response){
for(var i = 0; i < response.list_count; i++){
var newElement = document.createElement('div');
newElement.innerHTML = response.list[i].firstname;
document.getElementById("list").appendChild(newElement);
}
document.getElementById("list_count").innerHTML = "" + response.list_count; + "";
});
};

Answer

This is happening because every 3 seconds you read JSON file and append it to the already rendered (with all the data appended in previous runs) list with

document.getElementById("list").appendChild(newElement);

If you want to show only the content of the file once, then you should clean the target list div with one of the methods described in here: Remove all child elements of a DOM node in JavaScript

for example: $('#list').empty();

Alternatively, you need to keep track of what you have already added to the list, and append only the new entries, but that might be a bit more tricky, if there is no unique identifiers in the json data that you render.

So, with the first solutioin it will be something like:

list();
setInterval(list, 3000);
function list() {
$.getJSON('list.php',function(response){
        $('#list').empty();
        for(var i = 0; i < response.list_count; i++){
        var newElement = document.createElement('div');
        newElement.innerHTML = response.list[i].firstname;
        document.getElementById("list").appendChild(newElement);
        }
    document.getElementById("list_count").innerHTML = "" +  response.list_count; + ""; 
});
};