I translated a blog before, there is talk about this, today singled out for a chat.

preface

Events are often triggered by the user, which can cause problems in some cases:

  • Sending data to the background is frequently triggered by users, which causes pressure on the server

  • Some browser events (window.onresize, mousemove, etc.) are triggered very frequently and can cause browser performance problems

If you run into any of these problems, then you need to use these techniques.

Let’s start by explaining the differences between Throttling and Debouncing:

We need to take the elevator every day to go to work and live.

If someone enters the elevator (user triggers the event), we will leave after 10 seconds (program execution). If someone enters the elevator again (user triggers the event again within 10 seconds), we will have to wait 10 seconds again (re-timing).

Function throttling is more intuitive, someone into the elevator, start timing, every 10 seconds to transport once, if no one, standby.

How these two strategies are used will depend on your actual needs, but once you understand the idea, the rest is easy.

Function Throttling

Function throttling function throttling function throttling function

var throttle = function(fn, interval) { //fn is the function to execute, interval is the delay time
  var _self = fn,  // Save function references that need to be deferred
      timer,  / / timer
      firstTime = true;  // This is the first call

  return function() { // Returns a function that forms a closure to persist the variable
    var args = arguments.// Cache variables
        _me = this;

    if(firstTime) { // If this is the first call, do not delay the execution
      _self.apply(_me, args);
      return firstTime = false;
    }

    if(timer) { // If the timer is still running, the last delay has not been completed
      return false;
    }

    timer = setTimeout(function() { // Delay execution for some time
      clearTimeout(timer);
      timer = null;
      _self.apply(_me, args);
    }, interval || 500);
  };
};

/ / use
window.onresize = throttle(function() {
  // The code you want to execute
}, 500);Copy the code

In fact, the key to function throttling and function stabilization is the use of setTimeout. As an aside, once you have a thorough understanding of the internal operating principles of setTimeout and setInterval, you will become a JS master. 😝

Functions Debouncing

I personally prefer to use the function anti-shake strategy in development, but I can’t say who is better, adapt to different scenarios.

I also put the comments in the code:

function debounce(fn, interval, immediate) {
  //fn is the function to be executed
  //interval indicates the waiting time
  //immediate Determines whether to execute the command immediately
  var timeout;  / / timer

  return function() { // Return a closure
    var context = this, args = arguments; // Cache the variables first
    var later = function() {  // Encapsulate the code to be executed later
      timeout = null; // Clear timer after successful call
      if(! immediate) fn.apply(context, args);// It can be called only if it is not executed immediately
    };

    varcallNow = immediate && ! timeout;// Whether to call immediately, and if the timer exists, do not call immediately
    clearTimeout(timeout);  // Whatever the case, it is safest to clear the timer first
    timeout = setTimeout(later, interval);  // Delay execution
    if(callNow) fn.apply(context, args);  // If it is the first time triggered and immediate is true, the command is executed immediately
  };
};

/ / use
var myEfficientFn = debounce(function() {
  // What you have to do
}, 250);

window.addEventListener('resize', myEfficientFn);Copy the code

The code above has a clever design: var callNow = immediate &&! timeout; If timeout exists, a timer is running, which is not the first time it has been executed, and the code in if(callNow) is not executed.

conclusion

These two blocks of code are often used in development, and there is no reason not to apply them, either to accommodate requirements or to optimize performance.

In addition, I use this technique in jQuery source code, even in this era of framework rampant, or only the knowledge of the bottom can make me feel secure.

Friends who like this article can follow my wechat public number and push some good articles irregularly.

This article is from Rockjins Blog, please contact the author for reprinting. Otherwise, legal liability will be investigated.