0

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; + ""; 
});
};
Cross
  • 75
  • 7

2 Answers2

1

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; + ""; 
});
};
Community
  • 1
  • 1
Vladimir M
  • 4,403
  • 1
  • 19
  • 24
0

I have shared how to get length of JSON response.

var obj = JSON.parse(response);

var limit=Object.keys(obj).length;

for( var i = 0; i < limit; i++ ) {

}

I am not sure about response.list_count you are using. Is that a finite number?

Sanka
  • 1,294
  • 1
  • 11
  • 20
  • list_count is the count of rows in the database. if the i have 2 names in the database like (name1, name2) list_count = 2; – Cross Sep 20 '16 at 01:14