javascript - setTimeout doesn't work as expected -
in application loading user posts using ajax scroll down feature.
the loop iteration takes time, browser freezes until results displayed. implemented settimeout method fix that, reason flow doesn't go inside settimeout method on debugging.
also page blank, data not rendered.
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 var resp_json=responsejson[index]; var dateobj=resp_json.postcreationtime; resp_json.postcreationtime = moment(dateobj).format("h:mm a, ddd, mmm 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); });
when flow reaches settimeout next code hits jquery lib
am doing right or missing something?
note: responsejson data server fine. without settimeout data loaded on page.
settimeout takes argument-less function (https://developer.mozilla.org/en-us/docs/web/api/windowtimers/settimeout), having index
argument little odd. suspect index undefined responsejson[index]
throwing out of bound exception (as evidenced console.log(1)
showing per niloct's comment). if change code to:
$.each(responsejson, function (index) { settimeout(function() { // no index in argument list var resp_json=responsejson[index]; var dateobj=resp_json.postcreationtime; resp_json.postcreationtime = moment(dateobj).format("h:mm a, ddd, mmm 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(); }); });
i suspect work.
(edited take account jjaulimsing's comment not needing encapsulating function.)
Comments
Post a Comment