Same: to ease the page lag caused by frequent function calls and heavy computations

Different: Anti-shake turns multiple execution into last execution, throttling turns multiple execution into only one execution within a specified time.



As shown above, a vertical line represents a function call.


Image stabilization

Definition:

After an event is triggered, the callback function can be executed only once within a specified period of time. If the event is triggered again within a specified period of time, the specified period of time is restarted.

Two versions

There are two kinds of anti-shaking:

  • 1) Non-immediate version: event trigger -> delay -> execute callback function; If the event continues to be triggered during the delay, the delay will be repeated. Execute the callback function after the delay ends. Common example: is the input search box, the customer typed after a while will automatically search
  • 2) Immediate execution version: event trigger -> execute callback function -> delay; If the event continues to be triggered during the delay, the delay will be repeated. After the delay ends, the callback function is not executed. Common example: is for the button anti – click. For example, like, heart mark, favorites and so on have immediate feedback button.

// Buffeting: non-immediate versionfunction debounce (fn,delay){
    return function() {let arg = arguments,context = this;
        clearTimeout(fn.timer);
        fn.timer = setTimeout(function(){ fn.apply(context,arg); },delay); }} // The timer function with the option of immediate execution: // The idea is similar to the above, if the immediate execution, the timer does not contain the callback function, but after the callback function is executed, it only plays the role of delay and reset timer identifierfunction debounce(fun, delay = 500,immediate = true) {
    letTimer = null // Save the timerreturn function (args) {
        let that = this
        let _args = args
		if(timer) clearTimeout(timer); // The timer needs to be emptied regardless of whether it is executed immediatelyif (immediate) {
		    if(! Timer) fun.apply(that, _args) // If the timer does not exist, it indicates that the delay has expired. You can execute the function immediatelysetTimeout(function(){ timer = null; // The timer is automatically set to null when the time is up, which is not only convenient to determine the timer status, but also to avoid memory leakage}, delay)}else{// If it is not an immediate version, reset the timer and put the callback function into it timer =setTimeout(function(){ fun.call(that, _args) }, delay); }}}Copy the code


The throttle

Definition:

When an event is continuously emitted, the callback function can only be called once in a specified period of time. If this event is triggered again within the specified time, nothing is done and the timer is not reset.

Comparison with anti-shake:

Stabilization is to turn multiple executions into the last execution, and throttling is to turn multiple executions into only one execution within a specified time. Generally, the timer is not reset. That is, no if (timer) clearTimeout(timer); (except timestamp + timer version)

Application Scenarios:

Two conditions: (1) the customer fires events frequently in succession; (2) the customer no longer only cares about the feedback after the “last” operation. It’s continuous feedback during the operation. Such as:

  • Click the mouse repeatedly to trigger, click events in the specified time only triggered once (only triggered once per unit time)
  • Listen for rolling events, such as whether to slide to the bottom to automatically load more, and throttle

// Fun refers to the callback function, which I will not writefunction throttle(fun, delay = 500) {
    letprevious = 0; // Record the timestamp of the last trigger. This is initially set to 0 to ensure that the callback is triggered the first timereturn function(args) {
        letnow = Date.now(); // Record the timestamp when triggered at this momentlet that = this;
        let _args = args;
        if(now-previous > delay) {// If the time difference is greater than the specified time, fun.apply(that, _args); previous = now; }} // Timer version:function throttle(fun, delay = 500) {
    let timer;
    return function(args) {
        let that = this;
        let _args = args;
        if(! Timer) {// If the timer does not exist, set a new timer, and then execute the callback, and set the timer to null timer =setTimeout(function(){ timer = null; Fun. apply(that, _args)}, delay)}}} Implement the first trigger can immediately respond, after the trigger can also have a response (this version is the most practical work requirements) // this version of the main idea is a timestamp version, the function of the timer is only to execute the last callbackfunction throttle(fun, delay = 500) {
     let timer = null;
     let previous = 0;
     return function(args) {
             let now = Date.now();
             letremaining = delay - (now - previous); // How much time is left before the specified timelet that = this;
             let_args = args; clearTimeout(timer); // Clear the timerif (remaining <= 0) {
                    fun.apply(that, _args);
                    previous = Date.now();
              } else {
                    timer = setTimeout(fun, remaining); }}}} {}}}}}}}Copy the code


Reference:

(1) anti – shake and throttling

7 minutes to understand the throttling, anti-shaking and application scenarios of JS