使用jquery或javascript延迟无限滚动

bsw*_*ton 0 javascript jquery infinite-scroll

我有一个jquery脚本正确加载无限滚动设置的新页面.我想要做的是这样当你说距离底部300px时,它会加载更多.我现在能够做到这一点,但遗憾的是滚动寄存器多次,ajax加载页面的其余部分.我试过setTimeout无济于事.

        (function(){

            //inner functions will be aware of this
            var currentPage = 1;

                $(window).scroll(function() {

                if($(window).scrollTop() + $(window).height() > $(document).height() - 300) {

                    $.ajax({
                        type: "GET",
                        url: "posts/page/" + currentPage,
                        data: "",
                        success: function(results){
                            $(".container").append(results).masonry('reload');
                        }
                    })
                    setTimeout(currentPage++,3000);

                }

            });

        })();
Run Code Online (Sandbox Code Playgroud)

zer*_*kms 6

通过此修改,如果之前尚未完成,则不执行另一个ajax请求:

(function(){

    //inner functions will be aware of this
    var currentPage = 1,
        currentXHR;

        $(window).scroll(function() {

        if($(window).scrollTop() + $(window).height() > $(document).height() - 300) {

            if (currentXHR) {
                return;
            }

            currentXHR = $.ajax({
                type: "GET",
                url: "posts/page/" + currentPage++,
                data: "",
                success: function(results){
                    $(".container").append(results).masonry('reload');
                },
                complete: function() {
                    currentXHR = null;
                }
            })

        }

    });

})();
Run Code Online (Sandbox Code Playgroud)