Read the function of image stabilization and throttling in one article

What is anti-shake and throttle?

"Anti-shake"

Scenario: While entering the name, go to the server to verify whether the name is duplicated. If the code is not restricted, input a request once; input multiple times to trigger the event

The callback function is executed after the event is triggered n seconds, and if it is triggered again within n seconds, the timer is re-timed

 Suppose a scene: the mouse moves over a div to trigger the onmousemove event, and the text inside it will display the current mouse coordinates.

Anti-shake: Function anti-shake, where the jitter is the meaning of execution, and the general jitter is continuous, multiple times. Assuming that the function continues to execute multiple times, we want it to calm down and execute again. That is, when the event is continuously triggered, the function is not executed at all, and it is executed after a period of time after the last trigger ends.

Break down the requirements:

  • Continuous triggering does not execute
  • Execute after a period of not triggering

 So how to achieve the above goals?

  •  If it is executed within the untriggered time, then a timer is needed,
  •  Call the function we want to execute in the timer, pass in arguments, encapsulate a function, let the continuously triggered event listen to the function we encapsulate, and pass the target function as a callback, the second point is achieved ,
  •  Look at the first point: continuous triggering does not execute. Let's think about it first, what makes our function execute? Is setTimeout above.
  •  OK, then the problem now becomes continuous triggering, and there can be no setTimeout, so that when the continuous triggering is continued, the timer is cleared .

"Throttle"

Throttling will be used in input and keyup to trigger events such as resize and touchmove more frequently. Throttling will force the function to execute at a fixed rate. The concept of throttling can be imagined as a dam. You built a dam in a river channel. You cannot let the water flow. You can only let the water flow slower. In other words, you can't let the user's methods not be executed. If you do this, it is "anti-shake".

 Throttling means that the function is executed in a controlled manner, rather than being executed once without uncontrolled triggering. What is temperance? It is triggered once in a period of time.

 Break down the requirements:

  •  Continuous triggering does not execute multiple times
  •  To execute at a certain time

 So how to achieve the above goals?

  •  Continuously triggered, and will not be executed, but will be executed when the time is up. Grab a key point " time to execute. "
  •  To control the timing of execution, we can do it through a switch, combined with the timer setTimeout.
  •  The prerequisite for the execution of the function is that the switch is opened, and when the trigger is continued, the switch is continuously closed.
  •  Wait until the setTimeout time is up and then turn on the switch , the function will be executed.

 Note: The result of the execution of the throttle function here is the call of its internal return function, which means that the event monitoring by the mouse is actually this returned function, and it is continuously triggered by it.

       The throttle function only provides a scope, and the internal closure declares a run switch variable.

       Since the variable closure run will always exist and not be destroyed, and let run = true is only declared once in this closure (local scope), but it will not be continuously executed, so the internal judgment of the return function It will not be overwritten by it.

 to sum up:

 Anti-shake and throttling cleverly use setTimeout to control the timing of function execution. The advantages are obvious, performance can be saved, and complex business logic can not be triggered many times and cause page stalls.

 

 Attach the complete code:

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<style>
  #container {
    width: 500px;
    height: 200px;
    background: #ccc;
    font-size: 20px;
    text-align: center;
    line-height: 200px;
  }
</style>
<body>
  <div id="container"></div>
</body>
<script>
// 防抖
function debounce(func, delay){
  let timeout;
  return function() {
    clearTimeout(timeout)
    timeout = setTimeout(()=>{
      func.apply(this, arguments)
    },delay)
  }
}
const container = document.querySelector('div');
// 调用方法
container.onmousemove = debounce(function(e){
  container.innerHTML = `clientX = ${e.clientX},clientY ${e.clientY}`
},1000);

// Throttle 
function throttle (func, delay) {
  let run = true;
  console.log ( 'When triggered ' , run);
   return  function () {
    console.log ( ' Return function content ' , run); 
     if ( ! run) {
       return  false  // If the switch is closed, the following code will not be executed 
    }
    console.log ( 'After judging whether the switch is closed or not ' , run);
    run =  false ; // If it continues to be triggered, run is always false, and it will stop at the upper judgment 
    console.log ( 'After the switch is turned off ' , run);
    setTimeout(() => {
      func.apply(this, arguments);
      run = true;
      console.log ( 'After the switch is turned on ' , run);
    }, delay)
  }
}
const container = document.querySelector ( ' div ' );
 // Call method 
container.onmousemove = throttle ( function (e) {
  container.innerHTML = `clientX = ${e.clientX},clientY ${e.clientY}`
},1000);
</script>
</html>

 

 

 

 

Open in PDFlux
no data

Guess you like

Origin www.cnblogs.com/cuixiaohua/p/12709663.html