JS function tremble

This is the first day of my participation in Gwen Challenge

A, what is function tremble

Concept: A function can only be executed once in n seconds after an event is triggered. If an event is triggered again within n seconds after the event is triggered, the delay time of the function is recalculated.

For example, 🌰, when riding an elevator, if the elevator detects someone coming in (trigger event), it will wait 10 seconds longer, and if another person comes in (trigger event within 10 seconds), the elevator will wait another 10 seconds. In the above example, the elevator does not close the door until it detects someone entering for 10 seconds, so the key to “function stabilization” is to wait a certain amount of time after an event has occurred before performing a specific action.

Why do I need function stabilization

In the process of front-end development, some events, such as Onresize, Scroll, Mousemove,mousehover, etc., will be triggered frequently (many times in a short time). If there is no restriction, it may be executed dozens or hundreds of times within a second. If other functions are executed within these functions, In particular, performing functions that manipulate the DOM (which is performance expensive for browsers) can waste computer resources, slow down programs, and even cause browsers to freeze and crash. This kind of problem is obviously fatal.

In addition, repeated Ajax calls in a short period of time can not only confuse data relationships, but also cause network congestion and increase server stress, which obviously needs to be addressed.

Realize the principle of

The main point of function stabilization is that a setTimeout is needed to assist the implementation and delay the execution of the required code. If the method fires more than once, clear the last recorded delay with clearTimeout and restart the timer. If the event is not retriggered during the timing, the object code will be executed after the delay time is finished.

    const debounce = (fn,wait) = >{
        let timer = null;
        return () = >{
            if(timer ! =null) {clearTimeout(timer);
            }
            timer = setTimeout(fn,wait)
        }
    };
    let handle = () = >{
        console.log(Math.random());
    }
    window.addEventListener("resize",debounce(handle,1000))
Copy the code

What is function throttling

Function throttling refers to the execution once every certain period of time, that is, to reduce the frequency, to optimize the high frequency operation into low frequency operation, usually using scenarios: scrollbar events, resize events, animation, etc., usually every 100~500 ms execution.

Realize the principle of

The timer version of the throttling function focuses on using closures to save timer variables and has two features:

  • N Seconds after the first execution (timer will be triggered when the time is up);
  • The throttling function is executed once more after the trigger is stopped (since the function is delayed and its task is already in the queue when the trigger is stopped, it is executed once more after the stop).

Usage scenarios

  • Lazy load, scroll load, load more or listen for scroll bar position;
  • Baidu search box, search association function;
// Timer scheme
function throttle(fn,wait){
    var timer = null;
    return function(){
        var context = this;
        var args = arguments;
        if(! timer){ timer =setTimeout(function(){
                fn.apply(context,args);
                timer = null;
            },wait)
        }
    }
}
    
function handle(){
    console.log(Math.random());
}
    
window.addEventListener("mousemove",throttle(handle,1000));
Copy the code