Underscore.js Debounce不能正常使用Scroll

Underscore.js Debounce not Working Properly with Scroll

本文关键字:常使用 Scroll 不能 js Debounce Underscore      更新时间:2023-09-26

我正在尝试使用_.debounce下划线.js函数来限制发送的AJAX POST请求的数量。

我的代码应该只执行AJAX一旦用户已经滚动到页面的底部,我已经尝试使用_.debounce在发送另一个请求之前等待2秒。一旦我滚动到底部,AJAX就会正确执行,但是,如果我在到达底部后继续滚动,在2秒内就会发送另一个AJAX请求。

我也试过使用_.throttle

function ajaxFunction() {
        $.ajax({
            type: "POST",
            url: "SearchResults",
            data: { skipAmount: $('.product-box').length, search: search },
            success: function (response) {
                if (response != null && response.success) {
                    $('#productcontent').append(response.responseText);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                if (debug) {
                    alert(XMLHttpRequest.responseText);
                    alert(textStatus);
                    alert(errorThrown);
                }
            }
        });
    }
    function debounceAjaxFunction() { _.debounce(ajaxFunction(), 2000); }
    $(window).scroll(function () {
        if ($(window).scrollTop() + $(window).height() == $(document).height()) {
                    debounceAjaxFunction();
        }
    })

您正在调用debounce参数中的函数

    _.debounce(ajaxFunction(), 2000);

当你只需要传递它的引用作为参数

    _.debounce(ajaxFunction, 2000);
然后设置一个变量,从滚动函数 调用
   var debounceAjaxFunction = _.debounce(ajaxFunction, 2000);

文档在这里供参考http://underscorejs.org/#debounce,相关部分是

    var lazyLayout = _.debounce(calculateLayout, 300);