Use function throttling to realize the stop of monitoring scroll bar

When we do front-end development, sometimes we will receive a request to monitor the scrolling of the scroll bar and the stop of the scroll bar. To monitor the scrolling of the scroll bar is very simple, just use window.addEventListener('scroll', function () { } ) It can be realized, but if you want to monitor the stop of the scroll bar, it seems not so simple. After all, js does not have such a monitoring event for us. At this time, you can use the method of function throttling to realize monitoring

The basic idea of ​​function throttling is to set a timer, clear the last timer when running the code within a specified time interval, and set another timer to execute until the function request stops and exceeds the time interval.
In javascript advanced programming, a method is defined as follows:

function throttle(method,context){
    clearTimeout(method.tId);
    method.tId=setTimeout(function(){
        method.call(context)
    },300)
}

The application looks like this in our requirements:

window.addEventListener('scroll', function () {
                _this.show = false;  //滚动时执行的方法
                clearTimeout(_this.isInterval);  //滚动时清除定时器
                _this.isInterval = setTimeout(function(){
                    _this.show = true;
                },500)  //当停止滚动时定时器执行
            })

Using this method not only meets the requirements, but also releases the performance of the browser, avoiding the behavior of constantly monitoring the scroll bar when scrolling

Guess you like

Origin blog.csdn.net/weixin_42252416/article/details/86505998