js realizes function anti shake and throttling

Conceptual understanding

Anti shake: the callback is executed after the event is triggered for n seconds. If the event is triggered again within n seconds, the timing will be re timed.

Throttling: the function can only be triggered once in a unit time. If the function is triggered more than once per unit time, only one will take effect.

The difference between anti chattering and throttling of js function:

Function anti shake is performed only once in a certain period of time, while function throttling is performed at intervals.

Personal trample

1. After understanding the concepts of function anti shake and function throttling, we use closures to implement function anti shake and throttling, without considering the throttling. If the user has input before the next request, but will not make the request at this time, it will cause the last input text to obtain other events and change no request, i.e. missed request. Therefore, we need to add a setTimeout covering function When preparing the request, set a flag, i.e. whether the request has been sent or not. If the request is sent in the normal cycle, change it to true, otherwise it will be false. Use setTimeout to make the setTimeout slightly longer than the remaining events, and take the throttling timer request first;

2. If you use the arrow function, you do not need to save this.

code implementation

div>
    <div>
        <input type="text" id="unDebounce">
    </div>
    <div>
        <input type="text" id="debounce">
    </div>
    <div>
        <input type="text" id="throttle">
    </div>
</div>
// Function anti chattering throttling
var elem1 = document.getElementById("unDebounce")
var elem2 = document.getElementById("debounce")
var elem3 = document.getElementById("throttle")
// No anti shake
function ajax1(value){
    console.log("No chattering, no throttling")
    console.log(value)
}

elem1.addEventListener('keyup',function (e) {
    ajax1(e.target.value);
})

// Anti shake
function ajax2(value) {
    console.log(value)
}
function debounce(func,delay){
    console.log("Function anti shake")
    let timer = null;
    return function(...args){
        if(timer){
            console.log("Clear timer")
            clearTimeout(timer)
        }
        timer = setTimeout(()=>{
            console.log("Retime")
            func.call(this,...args)
        },delay)
    }
}
let debounceFn = debounce(ajax2,1000)
elem2.addEventListener('keyup',function (e) {
    debounceFn(e.target.value);
})

// // throttle
function ajax3(value){
    console.log(value)
}
function throttle(func,delay){
    console.log("Function throttling")
    let lastTime = 0;
    let timer = null;

    return function (...args) {
        let flag = false ; // Data hasn't been sent yet
        let now = +new Date().getTime();
        if(timer){
            clearTimeout(timer)
        }
        if(now-lastTime>=delay){
            console.log("If the current time is greater than the set time, start executing the function")
            func.apply(this,args)
            console.log("time1",new Date().getTime())
            lastTime = now;
            flag = true; // Data sent
        }else{
            timer = setTimeout(()=>{
                if(!flag){ // If the data is not sent successfully, go ahead and send the request
                    func.apply(this,args)
                    console.log("time2",new Date().getTime())
                }
            },delay-(now-lastTime)+1000) // setTimeout More, priority periodic requests
        }
    }
}
let throttleFn = throttle(ajax3,5000)
elem3.addEventListener('keyup',function (e) {
    throttleFn(e.target.value);
})

Tags: Javascript

Posted on Fri, 22 May 2020 12:54:33 -0400 by emopoops