Can I declare logic on jQuery for the start and en

2019-01-15 21:37发布

问题:

I would like to setup logic for when the user begins scrolling around the page and after the scrolling is finished, how can I accomplish this?

I want to avoid the below as it means my logic will be fired repeatedly unnecessarily

$(window).scroll(function(){
    console.log("scrolling");
});

回答1:

You can try defining you're own debounced events. A (very crude) implementation would look something like this:

var t, l = (new Date()).getTime();

$(window).scroll(function(){
    var now = (new Date()).getTime();

    if(now - l > 400){
        $(this).trigger('scrollStart');
        l = now;
    }

    clearTimeout(t);
    t = setTimeout(function(){
        $(window).trigger('scrollEnd');
    }, 300);
});

See: http://www.jsfiddle.net/yijiang/fGmbe/ for a live demo