这是因为onscroll事件会在时间的短短多次调用。您可以使用类似debouncing
反弹功能不允许在给定时间范围内多次使用回调。将回调函数分配给频繁触发事件时,这一点尤为重要。
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
你会通过防抖动功能来执行功能,以毫秒为单位的消防速率限制。下面是修改后的代码,以满足您的要求:
var myEfficientFn = debounce(function() {
if($(window).scrollTop() + $(window).height() > $(document).height() - 200) {
$("#pwip__loadmore").click();
}
}, 1000);
window.addEventListener('scroll', myEfficientFn);
参考
DavidWalsh
怎么样'setTimeout'? –
我尝试了几种方法无济于事,你会怎么做? – Sergi