2008-11-01 9 views
0

다음 javascript는 간격을 설정하여 json 개체 목록의 새 항목이 목록 상단에 천천히 추가되지만 대신 모두 동시에 추가됩니다.자바 스크립트에서 시간 간격을 어떻게 설정할 수 있습니까?

<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

내가 너라면 약간 다른 방식으로 해결할 것입니다. 모든 데이터를 페이지에 추가하지 말고 숨기 만하면 언제든지 공개 할 수 있습니다. 그렇게하면 종결과 그 밖의 것들에 대해 걱정할 필요가 없습니다.

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 
    } 
} 
관련 문제