2

我有一个非常简单的脚本可以正常工作。但是,我想将新结果的附加延迟 3 秒,以避免服务器过载。因此,当您到达页面末尾时,应该显示加载图像 3 秒,然后应该发出 ajax 请求。

我如何使“延迟”?

这是脚本:

$(window).scroll(function(){
    if($(window).scrollTop() == $(document).height() - $(window).height()){
         var lastID = $('div.row-details').last().attr("id");

         $('div#loadmoreajaxloader').show();

         $.ajax({url: "/projects.php?lastID=" + lastID,
            success: function(html){
                if(html){
                       $("#maintable").append(html);
                       $('div#loadmoreajaxloader').hide();
                 }else{
                       $('div#loadmoreajaxloader').html('<center>No more posts to show.</center>');
                   }
              }
           });
      } 
});
4

3 回答 3

0

for your remark: "i have tried that, it works just for the first time i hit the end of the page. and then, everything becomes a mess :( ",

can you try clearTimeout();? if you scroll condition is met again within 3 seconds, ajax call will not be made. probably solves your mess up issue.

var timeoutId;
    $(window).scroll(function(){
        if($(window).scrollTop() == $(document).height() - $(window).height()){
             var lastID = $('div.row-details').last().attr("id");
             clearTimeout(timeoutId);   // no problem if invalid id, there is no exception     
             $('div#loadmoreajaxloader').show();
               timeoutId = setTimeout(function() {
                    $.ajax({
                        url: "/projects.php?lastID=" + lastID,
                        success: function(html) {
                            if (html) {
                                $("#maintable").append(html);
                                $('div#loadmoreajaxloader').hide();
                            } else {
                                $('div#loadmoreajaxloader').html('<center>No more posts to show.</center>');
                            }
                        }
                    });
                }, 3000);

          } 
    });
于 2012-07-09T14:10:24.933 回答
0

有些解决方案不需要您在第一次AJAX 调用前等待 3 秒。查看下划线的throttle()功能。

于 2012-07-09T14:18:32.690 回答
0

将 AJAX 调用包装在传递给 的匿名函数中setTimeout(),如下所示:

setTimeout(function() {
    $.ajax({
        url: "/projects.php?lastID=" + lastID,
        success: function(html) {
            if (html) {
                $("#maintable").append(html);
                $('div#loadmoreajaxloader').hide();
            } else {
                $('div#loadmoreajaxloader').html('<center>No more posts to show.</center>');
            }
        }
    });
}, 3000);
于 2012-07-09T13:02:48.703 回答