在我的應用程序中,我使用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
我這樣做是正確的或丟失的東西下面的代碼?
注意:我得到服務器的responseJson數據正常。沒有setTimeout,數據將加載到頁面上。
'的console.log(1);'的'setTimeout'回調的第一行之前,是否在控制檯打印嗎? – Niloct
我把它放在setTimeout之前,之後(function(index){;它在控制檯中打印了10次;但是它也表示未捕獲的TypeError:無法讀取未定義的屬性'postCreationTime'10次。無法讀取響應JSON – underdog
在$ .each中使用封裝函數是否有一個特定的原因?它與直寫$ .each(responseJson,function(index){setTimeout(function(){...)有什麼不同? – jjaulimsing