views:

499

answers:

2

I have a json object 'items' which has few items that I want to show 2 of them every 2 seconds. How would I do that? so, it displays items in division1 every few seconds instead of showing all at once. Eg. get all items every 5 seconds and show 4 items every second for 20 items.

<table id="division1" >
    <thead>
     <th>Name</th>
     <th>Score</th>
    </thead>
    <tbody></tbody>
</table>



function render_items(division){
    var tablebody ="";
     $.each(division.items, function (i,item){
      var tablerow ="<tr>"
       +"<td>"+item.name+"</td>"
       +"<td>"+item.score+"</td>"
       +"</tr>";
      tablebody = tablebody+tablerow;

        //$('#test').append(division.name+' '+i+' '+robot.name+'<br>');
     }
     );
     $('#'+division.name+" tbody").html(tablebody); 
}

function poll(){
    $.post("data.php", {getvalues: 0}, 
    function (data, status){
     $.each (data.divisions, function(i,division){
      render_items(division);  

     }); 
    },
    'json'
    );
    setTimeout('poll()',5000);
}

$(document).ready(function() {
    poll();

}
A: 

setTimeout can take a function as the first argument, it can then take advantage of closure vars to keep track of the data and the count.

jayrdub
+2  A: 

it would probably be simplest to hide all the rows, then show a range of them every second with something like:

function startShow(table) {
    var index = 0;
    var trs = table.find("tbody tr");
    function update() {
        if (index >= trs.length) {
            index = 0;
        }
        trs.hide().slice(index, index + 4).show();
        index += 4;
        setTimeout(update, 1000);
    }
    update();
}

and then call it with

startShow($("#division1"));
cobbal
thanks, that works. Do you have any idea how I wound modify that for many table names (in a somewhat clean way)?
pvsnp
updated it to work with multiple tables, also a little cleaner now.
cobbal