setTimeout无法按预期工作

und*_*dog 1 javascript ajax jquery

在我的应用程序中,我使用ajax向下滚动功能加载用户帖子.

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);
        });
Run Code Online (Sandbox Code Playgroud)

当流程达到setTimeout时,它命中的下一个代码是jquery lib

在此输入图像描述

我做得对还是错过了什么?

注意:我从服务器上获得了responseJson数据.如果没有setTimeout,数据将加载到页面上.

sya*_*ani 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();
        });
    });
Run Code Online (Sandbox Code Playgroud)

我怀疑它会起作用.

(编辑以考虑jjaulimsing关于不需要封装功能的评论.)