Function anti – shake and throttling

Image stabilization (debounce)

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

Anti – shake types are divided into

  1. Not an immediate release
  2. Immediate execution version
  3. Synthetic version anti-shake

Anti-shake application scenarios

  • The login and SMS buttons prevent users from clicking too fast and sending multiple requests
  • The number of resize times is too frequent when the browser window is resized, which results in too much calculation. In this case, you need to resize the browser window once
  • The text editor saves in real time and saves after one second when there is no change operation

Not an immediate release

The non-immediate version means that the function is not executed immediately after the event is fired, but n seconds later. If the event is fired within n seconds, the function execution time is recalculated.

/ * * *@description: 
 * @param {*} Func triggers the event *@param {*} How long to wait for an event *@return {*}* /
        function debounce(func, wait) {
            let timeout;
            return function(){
                // Get the current scope and parameters
                const context = this;
                const args = [...arguments] 
                // If the current timeout exists
                // Clear the timer and wait for the wait time to pass and execute the event again
                if(timeout) clearTimeout(timeout)
                // Execute the events passed in periodically
                timeout = setTimeout(() = >{
                    func.apply(context,args)
                },wait)  
            }
        }
Copy the code

Immediate release

The immediate execution version means that the function is executed immediately after the event is fired, and then the effect of the function cannot be continued until the event is fired for n seconds.

function debounce(func,wait) {
  let timeout;
  return function () {
      const context = this;
      const args = [...arguments];
      if (timeout) clearTimeout(timeout);
      constcallNow = ! timeout; timeout =setTimeout(() = > {
          timeout = null;
      }, wait)
      if (callNow) func.apply(context, args)
  }
}

Copy the code

Code parsing

When debounce is called, the first time it comes in, timeout is false, so callNow is true, and it immediately executes the func function, When the timeout value is true, the empty timer will be executed. At this time, timeout is false again. At this time, callNow is true again, and the func function will be executed again.

Keep looping like this:

When timeout is false, the func function is executed immediately.

When timeout is true, it executes clearTimeOut, which in turn is false, and callNow =! Timeout, the func function will be executed immediately.

Synthetic version anti-shake

Pass Boolean to decide which version to execute.

  • trueFor immediate release
  • falseIs not the immediate execution version

debounce(func,1000,true)

/ * * *@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 () {
    const context = this;
    const args = [...arguments];
    if (timeout) clearTimeout(timeout);
    if (immediate) {
      constcallNow = ! timeout; timeout =setTimeout(() = > {
        timeout = null;
      }, wait)
      if (callNow) func.apply(context, args)
    }
    else {
      timeout = setTimeout(() = >{ func.apply(context, args) }, wait); }}}Copy the code

The throttle

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

There are two implementations of throttling:

  1. Timestamp version
  2. Timer version

Throttling Application Scenarios

  1. scrollEvent, calculate position information every second, etc
  2. Browser plays events, calculates progress information every second, and so on
  3. inputWhen the input box searches for content, it can control how many s requests are executed, avoiding multiple requests and saving performance.

Timestamp version

function throttle(func, wait) {
    var previous = 0;
    return function() {
        let now = Date.now();
        let context = this;
        let args = arguments;
        if(now - previous > wait) { func.apply(context, args); previous = now; }}}Copy the code

Timer version

function throttle(func, wait) {
    let timeout;
    return function() {
        let context = this;
        let args = arguments;
        if(! timeout) { timeout =setTimeout(() = > {
                timeout = null;
                func.apply(context, args)
            }, wait)
        }

    }
}

Copy the code

Code parsing

When throttle is throttle, timeout defaults to undefined, and! When timeout is true, the timer is executed and timeout is null (false). Throttle is throttle again. Timeout is true again, and the timer is executed again.

** Control of throttling is achieved through the timeout state **

conclusion

  • Anti – shake: after triggering the event, the event can be executed after a certain period of timeExecuted immediatelyCan also beWait a certain amount of time before executing

  • Throttling: Controls traffic and requests only once per unit of time to avoid multiple triggering events that affect server performance.

conclusion

❤️ attention + like + collection + comment + forward ❤️, the original is not easy, encourage the author to create better articles pay attention to the public number front-end self-study community, you can get more front-end high-quality articles! After paying attention to the reply keyword “add group”, you can join the “front-end self-study communication group”, learning progress together. After paying attention to add my wechat pull you into the technical exchange group welcome to pay attention to the public number, more wonderful articles only in the public number push

reference

Github.com/mqyqingfeng…