Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

scenario

In front end development, we often bind events that are constantly firing, but sometimes we don’t want to execute functions that often while events are constantly firing. Such as:

  • Window object frequently onresize, onScroll and other events
  • Drag mousemove event
  • Shooter mouseDown, keyDown events
  • Text input, auto-complete keyup event

In this case, anti – shake and throttling is a good solution.

Anti-shake and throttling

Debounce

The so-called shaking prevention means that the function can only be executed once within n seconds after the event is triggered. If the event is triggered again within N seconds, the function execution time will be recalculated.

 
/ * * *@desc Function stabilization *@param Func function *@param Number of milliseconds to delay wait execution *@param Immediate true The table is executed immediately. False The table is not executed immediately */
function debounce(func,wait,immediate) {
    let timeout;

    return function () {
        let context = this;
        let args = arguments;
​
        if (timeout) clearTimeout(timeout);
        if (immediate) {
            varcallNow = ! timeout; timeout =setTimeout(() = > {
                timeout = null;
            }, wait)
            if (callNow) func.apply(context, args)
        }
        else {
            timeout = setTimeout(function(){ func.apply(context, args) }, wait); }}}Copy the code

Throttle

Throttling refers to firing events continuously but executing the function only once in n seconds.

 
/ * * *@desc Function throttling@param Func function *@param Number of milliseconds to delay wait execution *@param Type 1 table timestamp version, 2 table timer version */
function throttle(func, wait ,type) {
    if(type===1) {let previous = 0;
    }else if(type===2) {let timeout;
    }
    return function() {
        let context = this;
        let args = arguments;
        if(type===1) {let now = Date.now();
​
            if(now - previous > wait) { func.apply(context, args); previous = now; }}else if(type===2) {if(! timeout) { timeout =setTimeout(() = > {
                    timeout = null;
                    func.apply(context, args)
                }, wait)
            }
        }
    }
}
Copy the code

The end of the

As a small white I have not too much use of anti – shake and throttling, here is a summary of it