如何在第一个之后延迟下一个滚动事件?

时间:2014-02-26 14:13:03

标签: jquery scroll delay

我有这个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()函数的结果:

  

ms:458 ms:505

第一次和下一次滚动之间的差异发生得太快,只有47毫秒。因此,我得到了奇怪的结果。我需要至少1秒的延迟。

我该如何做到这一点?

1 个答案:

答案 0 :(得分: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