Underscore.js Debounce 无法与 Scroll 一起正常工作
Underscore.js Debounce not Working Properly with Scroll
我正在尝试使用 _.debounce
Underscore.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);
我正在尝试使用 _.debounce
Underscore.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);