【问题标题】:setTimeout stop scrolling functionsetTimeout 停止滚动功能
【发布时间】:2019-06-11 06:28:21
【问题描述】:

我有这个滚动功能可以检查何时到达 div id 的末尾:

function loadOldPosts() {

        $.ajax({
            url: "https://www.example.com/go.php",
            method: "post",
            data:{
                postID: postID
            },
            dataType:"json",
            success:function(data)
            {
                if (data) {

                    setTimeout(loadOldPosts, 5000);

                }
            }

        });

    }

$(window).scroll(function() {

    var $this = $(this);

    if ($this.scrollTop() + $this.height() >= $('#wall_posts').offset().top + $('#wall_posts').height() ) { 
        loadOldPosts();
    } 

});

我正在尝试使 loadOldPosts 运行后,它必须等待 5 秒才能再次运行。我虽然可以使用 setTimeout 函数完成此操作,但它似乎不起作用。

如何才能使该功能最多每 5 秒运行一次?

谢谢!

【问题讨论】:

    标签: javascript jquery scroll settimeout


    【解决方案1】:

    您可以使用以下示例等待下一次调用直到 ajax 成功/错误:

    var loading  = true;
    function loadOldPosts(){
       if(loading){
         loading  = false;
         $.ajax({
          ...,
          success:function(data){
             loading  = true;
          },
          error:function(data){
             loading  = true;
          }
         })     
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多