2014-02-26 20 views
0

我有這個jQuery功能,就像一個無限滾動:如何延遲第一個之後的下一個滾動事件?

$('.box.scroll').bind('scroll', function() { 
if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) { 
    console.log(".scrollTop() = " + $(this).scrollTop() + " .innerHeight() = " + $(this).innerHeight() + " scrollHeight = " + $(this)[0].scrollHeight); 
    console.log("ms: " + new Date().getMilliseconds()); 

    getData(); 
} 
}); 

這是什麼得到了打印到console.log()功能結果:

毫秒:458毫秒:505

第一次和第二次滾動之間的差異發生得太快,只有47毫秒。正因爲如此,我得到了奇怪的結果。我需要至少1秒的延遲。

我該如何做到這一點?

+0

你查的setTimeout和setInterval JavaScript函數? https://developer.mozilla.org/en/docs/Web/API/window.setTimeout –

+1

debounce事件,請參閱例如:http://benalman.com/projects/jquery-throttle-debounce-plugin/ –

+0

該腳本的作品像任何光滑的工作一樣順利!做一個'AJAX'也會調用它,並且它描述了它也被用於這個。偉大的劇本,非常感謝你!除非你回答這個問題,否則不能接受:) – Quoter

回答

0

您可以使用類似這樣

var addScrollListener = (function(){ 
    var interval = 300, 
     checkInterval = interval+75; 
    var last = 0, timer = null, queue = false, el; 
    function check(){ if(queue) main(false); } 
    function main(addQueue){ 
     clearTimeout(timer); 
     last = new Date().getTime(); 
     queue = false; 
     if(addQueue) timer = setTimeout(check, checkInterval); 
     el.onscrollhandler.call(el); 
    } 
    function handler() { 
     el = this; 
     if(new Date().getTime() > last+interval) main(true); 
     else queue = true; 
    } 
    return function(el, f) { 
     el.onscroll = handler; 
     el.onscrollhandler = f; 
    }; 
})(); 

addScrollListener(element, handler); 

Demo

相關問題