這是因爲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