简体   繁体   中英

How to make scroll event to receive only one request at a time?

I am trying to trigger an action on scroll event when the user reaches a certain point in the web page.

So What I am facing right now is that the Scroll event fires too many times which messes the structure of the web page. I mean too much stuffs are loaded into the site suddenly which is exactly How I do not want it. Instead I have tried Debounce method in jQuery & also Throttle but none of them are working as because let me tell you.

DEBOUNCE can't keep to execute until when the user stops scrolling so if the user keeps scrolling continuously with no delays so the debounce function won't execute.

THROTTLE as it keeps executing after every given amount of time so It can miss the scroll place to fire there. So it's no help too.

What I Want Exactly ?

I want that whenever a user scrolls to the certain area of the web page so even if the page fires too much scroll events so it should only process one event and ignore the rest and then when the user scrolls down and then he reaches the area so then again it should only process one request.

IMP : Also I want to capture fast scrolling too as right now it's not firing any events on fast scrolling only when the user scrolls too much slowly. Something like the when even during fast scrolling the user passes the certain area of the web page so the event should fire.

Here is my Code :

    $i = 0;
    $(window).scroll(_.throttle(function() {
     // console.log($i++);
        if ($('.searchResult').length) {
            scrollTop = $(this).scrollTop();
            lastLiPos = parseInt($('.searchResult li:last-child').offset().top) - parseInt($(window).height());
            last12thRowLiPos = parseInt($('.searchResult li:nth-last-child(26)').offset().top) - parseInt($(window).height());
            if ((scrollTop > last12thRowLiPos && scrollTop < (last12thRowLiPos) + 150) &&
                $('#search_result_cont').attr('data-disable-load-result') === 'false'
            ) {
                var text = $.trim($("div#load_more").text());
                if (text !== "No More Results") {
                        $('div#load_more').trigger('click');
                    }
                if (text !== "No More Results") {
                    $('div.loading_animate').fadeIn(1000);
                } else {
                    console.log($.trim($("div#load_more").text()));
                }
            }
        }
    },100));

我认为您需要一些RXJS 过滤器魔术。我没有使用过它,但是有一个rxjs-jquery库。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM