2015-11-01 98 views
1

在我的應用程序中,我使用ajax向下滾動功能加載用戶帖子。setTimeout無法按預期工作

for循環迭代花費太多時間,瀏覽器凍結,直到顯示結果。所以我實現了一個setTimeout方法來解決這個問題,但由於某種原因,流程並沒有在調試時使用setTimeout方法。

此外頁面爲空白,數據不會呈現。

success : function(responseJson) { 
     $("#loadingdata").toggle(); 
     enableScrolling(); 

     if($.isEmptyObject(responseJson)){ 
      $("#noMorePosts").toggle(); 
      disableScrolling(); 
      paginationComplete=true; 
     } 

     $.each(responseJson, function (index) {  
      (function(index) { 
      setTimeout(function(index) { //the flow doesn't move inside this 
       var resp_JSON=responseJson[index]; 
       var dateObj=resp_JSON.postCreationTime; 
       resp_JSON.postCreationTime = moment(dateObj).format("h:mm a, ddd, MMM Do YY"); 
       var timeago = moment(dateObj).fromNow(); 
       resp_JSON.timeago = timeago; 
       resp_JSON.username=userName;    
       var post_template = $('#homepostcontainertemplate').html(); 
       Mustache.parse(post_template); 
       var post_info = Mustache.to_html(post_template, resp_JSON); 
       $('#homepublisherpostsdiv').append(post_info); 
       $('div').linkify(); 
      }); 
      })(index); 
     }); 

當流量達到的setTimeout它擊中的是jQuery的LIB

enter image description here

我這樣做是正確的或丟失的東西下面的代碼?

注意:我得到服務器的responseJson數據正常。沒有setTimeout,數據將加載到頁面上。

+1

'的console.log(1);'的'setTimeout'回調的第一行之前,是否在控制檯打印嗎? – Niloct

+0

我把它放在setTimeout之前,之後(function(index){;它在控制檯中打印了10次;但是它也表示未捕獲的TypeError:無法讀取未定義的屬性'postCreationTime'10次。無法讀取響應JSON – underdog

+1

在$ .each中使用封裝函數是否有一個特定的原因?它與直寫$ .each(responseJson,function(index){setTimeout(function(){...)有什麼不同? – jjaulimsing

回答

5

setTimeout使用無自變量函數(https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout),因此將index作爲參數有點奇怪。我懷疑這個索引是未定義的,所以responseJson[index]拋出了界限例外(如console.log(1)顯示按照Niloct的評論)。如果您將您的代碼更改爲:

$.each(responseJson, function (index) {  
     setTimeout(function() { // no index in the argument list 
      var resp_JSON=responseJson[index]; 
      var dateObj=resp_JSON.postCreationTime; 
      resp_JSON.postCreationTime = moment(dateObj).format("h:mm a, ddd, MMM Do YY"); 
      var timeago = moment(dateObj).fromNow(); 
      resp_JSON.timeago = timeago; 
      resp_JSON.username=userName;    
      var post_template = $('#homepostcontainertemplate').html(); 
      Mustache.parse(post_template); 
      var post_info = Mustache.to_html(post_template, resp_JSON); 
      $('#homepublisherpostsdiv').append(post_info); 
      $('div').linkify(); 
     }); 
    }); 

我懷疑它會起作用。

(編輯考慮到有關不需要封裝功能帳戶jjaulimsing的評論。)

+0

工作正常syaz謝謝 – underdog

+0

嗨Syaz,請你接受用戶名編輯請求我試圖從搜索引擎中刪除引用。提前致謝。 – jjaulimsing