When I meet a demand, the page needs to load a data table, but the request is very slow. If the user clicks the button for many times, the request will be triggered continuously. Because of the continuous request, the page will be constantly refreshed, which can be said to be particularly bad experience. So I have been thinking about how to solve this bug. Suddenly, I thought of anti-shake and throttling. I had not figured it out before. This time, I figured it out once and tried to solve the page bug.

Function image stabilization

The first consideration is anti – shake, what is anti – shake. On a page, events such as Click and mousemove can be executed many times in a short period of time, such as clicking a button many times, so if a single click causes a single request, it will cause memory overuse. So we listen to a timer, when the timer is clicked we use a timer to listen, set a certain time to trigger the event. In this case, if the button is clicked again, the timer will be replaced and the timer will start counting the time again. This is the principle of function chattering. Here is the original version of function chattering:

let timer = ""
export function debounce(fn,time){
    window.clearTimeout(timer);
    timer = setTimeout(()=>{
        fn()
    },time)
}
Copy the code

In the above code, however, time is an outer variable, which would pollute the environment, so we consider using closures to include variables in the parent scope, so that the variable is always confined to the local scope and does not pollute the entire environment.

export function debounce(fn,time){
    let timer;
    return ()=>{
        const _this = this;
        if (timer) clearTimeout(timer)
        timer = setTimeout(()=>{
            fn.apply(_this)
        },time)
    }
}
Copy the code

Function of the throttle

A different approach to reducing the number of triggers above is throttling. The idea is to have a function execute only once in a period of time. For example, we can use throttling function to encapsulate the previous mouse click triggered requests, which can effectively reduce the number of requests sent after the click. The code is very similar to the previous anti-shake.

export const throttle = (fn,time)=>{ let timer return ()=>{ const _this = this if (timer) return timer = SetTimeout (()=>{fn. Call (_this)}}Copy the code

The above is the idea and realization of anti-shake and throttling, and I hope it will be helpful for my project