繁体   English   中英

setTimeout无法正常工作

[英]setTimeout doesn't work as expected

在我的应用程序中,我正在使用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);
        });

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

在此处输入图片说明

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

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

setTimeout采用无参数函数( https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout ),因此将index作为参数有点奇怪。 我怀疑索引是未定义的,所以responseJson[index]会抛出绑定异常(如根据Niloct的注释显示的console.log(1) )。 如果将代码更改为:

    $.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关于不需要封装功能的评论。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM