Difference and implementation of JavaScript anti shake and throttling

  • 2021-11-29 22:48:55
  • OfStack

Directory 1, Anti-shake 2, Throttle 3, Summary

Foreword:

As a front-end development, there are two requirements

(1) Search requirements

The logic of search is to listen to user input events, and send the data to the back end after the user input is completed, and the back end returns the matching data, and the front end displays the data to the page. If the request is made as long as the user inputs, it will cause request pressure on the back end, and it is necessary to control the frequency of requests.

(2) The page loads data indefinitely

The logic of unlimited loading data on the page is to monitor the user scrolling event, and request the data of the next page to be displayed on the page during the user scrolling process. If you scroll to send a request, it will also cause back-end request pressure and need to control the frequency of requests.

The above two kinds seem to be the problem of controlling the frequency of requests, but there are subtle differences in requirements: search means that the user inputs many times in the input, and only after the user stops inputting briefly, he sends the request, at this time, he needs anti-shake to realize it. Scrolling loading data is to request every 1 period of time in the process of user scrolling the page. Even if user 1 scrolls straight, he will request it, instead of waiting for the user to stop scrolling. At this time, throttling is needed to realize it.

1. Anti-shake

Meaning:

The simple way of understanding is that the user triggers the event many times. In the event triggered by user 1, the event will not be executed, and the event will only be executed once after the user stops triggering the event for 1 period of time.

Achieve:


// @fn  Is the corresponding request data 
    // @ms  Is the time interval when the user triggers the event multiple times   Yes 1 Milliseconds 
    function debounce(fn, ms) {
        let timeout = null
        return function() {
            clearTimeout(timeout)
            timeout = setTimeout(() => {
                fn.apply(this, arguments)
            }, ms)
        }
    }

Principle:

Every time the user triggers an event, the execution will be delayed. Before setting the delay timer, the last delay timer will be cleared. In the end, only the interval between the user triggering this event continuously exceeds the parameters set by us ms The event will not fire once until milliseconds later

Test:


<input id="searchInput"/>
    function getData(){
        console.log(' Send a request ...')
    }
    document.getElementById('searchInput').oninput = debounce(getData, 800)
    //  If the user 1 Straight in input, no request will be sent 
    //  Only the user continuously enters the time interval exceeding 800ms Will request later 1 Secondary data, that is, the user is in 800ms You will request data only if there is no input in it 

2. Throttle

Meaning:

The simple way of understanding is that the user triggers the event many times, and the event will be executed once every 1 period of time and many times in the process of triggering the event directly by the user 1.

Achieve:


    // @fn  Is the corresponding request data 
    // @ms  Is the time interval when the user triggers the event multiple times   Yes 1 Milliseconds 
     function throttle(fn, ms){
        let flag = true
        return function(){
            if(!flag) return
            flag = false
            setTimeout(()=>{
                fn.apply(this, arguments)
                flag = true
            }, ms)
        }
    }

Principle:

One delay timer will be set every time the user triggers an event, but if the delay timer has been set, the next timer will be started after the last delay timer is executed, so that the user triggers the event directly, and the event will be executed once every one period of time

Test:


function getData(){
        console.log(' Send a request ...')
    }
    window.onscroll = throttle(getData, 800)
    //  In the process of scrolling, users will request data at intervals 


3. Summary

Throttling and anti-shake are essentially to control the frequency of event execution, but the timing of triggering events is essentially different. Anti-shake is to trigger events many times when the user stops triggering events and execute them once; Throttling means that the user triggers an event multiple times, and the event will be executed at intervals in the process of triggering multiple times.


Related articles: