简体   繁体   English

setTimeout停止滚动功能

[英]setTimeout stop scrolling function

I have this scroll function that checks for when the end of a div id reached: 我有这个滚动功能,检查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();
    } 

});

I'm trying to make it so that once loadOldPosts runs, it must wait 5 seconds before being able to run again. 我试图让它一旦loadOldPosts运行,它必须等待5秒才能再次运行。 I though I could accomplish this with setTimeout function but it does not seem to work. 我虽然可以使用setTimeout函数完成此操作,但它似乎不起作用。

How can I make it to that the function can only run once every 5 seconds at most? 我该如何才能使该功能最多每5秒运行一次?

Thanks! 谢谢!

You can do it with wait for next calling until ajax success/error using following example: 您可以使用以下示例等待下一次调用直到ajax成功/错误:

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

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

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