underdog underdog - 3 months ago 10
Ajax Question

setTimeout doesn't work as expected

In my application I am loading user posts using the ajax scroll down feature.

The for loop iteration takes too much time, browser freezes until the results are displayed. So I implemented a setTimeout method to fix that, but for some reason the flow doesn't go inside the setTimeout method on debugging.

Also the page is blank, data is 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 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);
});


When the flow reaches setTimeout the next code it hits is the jquery lib

enter image description here

Am I doing it right or missing something?

Note: I get the responseJson data from the server fine. Without the setTimeout the data is loaded on the page.

Answer

setTimeout takes an argument-less function (https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout), so having index as an argument is a little odd. I suspect that index is undefined so responseJson[index] is throwing out of bound exception (as evidenced by console.log(1) showing up as per Niloct's comment). If you change your code to:

    $.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();
        });
    });

I suspect it will work.

(edited to take into account jjaulimsing's comment about not needing the encapsulating function.)

Comments