views:

409

answers:

1

The following javascript should setup an interval so a new item from the list of json objects will be added to the top of the list slowly, but instead they are all added at the same time.

<script type="text/javascript">
 var json;
 var count = 0;
 $(document).ready(function() {
  $.ajax({
   type: "POST",
   url: "/Home/PublicTimeLine",
   data: "{}",
   contentType: "application/json; charset=utf-8",
   dataType: "json",
   success: function(msg) {
    json = eval(msg);
    createRow();
   }

  });
 });

 function createRow() {
  if (count < json.length) {
   var data = json[count];
   var row = document.createElement("div");
   $(row).hide();
   row.appendChild(document.createTextNode(data.text));
   $(document).find("#results").prepend(row);
   $(row).fadeIn("slow");
   count++;
   setTimeout(createRow(), 3000);
  }
 }
</script>

<div id="results">
</div>
+2  A: 

If I were you I'd tackle it in a slightly different way. Why not add all the data onto your page, but just hide it and only reveal when you want it. That way you don't have to worry about closures and whatnot.

var intervalId;
$.ajax({
    type: "POST",
    url: "/Home/PublicTimeLine",
    dataType : "json",
    success : function (msg) {
        var json = eval(msg); // is this even needed?
        $.each(json, function(ind, data) {
            $("<div></div>")        // use jQuery to create the div
                .hide()
                .text(data)        // you can use jQuery to add contents too. (use .html() if you need HTML)
                .prependTo('#results')
            ;
        });
        intervalId = setInterval(showRow, 3000);
    }
});
function showRow() {
    var $myDiv = $('#results div:hidden:last');
    if ($myDiv.length) {
        $myDiv.show('slow');
    } else {
        clearInterval(intervalId);    // none more to show, stop checking
    }
}
nickf