How to achieve stabilization and throttle

Anti-shake and the throttle is essentially not the same. Anti-shake is executed multiple times becomes the last execution, the throttle is repeatedly executed every so often become.

Image Stabilization: after the trigger event within the high frequency n seconds function only once, if n seconds high frequency event is triggered again, time is recalculated

Delay before calling the method are canceled each time the trigger event: Solution

 
 
function delayFun(fn) {
      let timeout = null; // 创建一个标记用来存放定时器的返回值
      return function () {
        clearTimeout(timeout); // 每当用户输入的时候把前一个 setTimeout clear 掉
        timeout = setTimeout(() => { // 然后又创建一个新的 setTimeout, 这样就能保证输入字符后的 interval 间隔内如果还有字符输入的话,就不会执行 fn 函数
          fn.apply(this, arguments);
        }, 500);
      };
}
function sayHi() {
      console.log('防抖成功');
 }

var box= document.getElementById('inp');
box.addEventListener('input',delayFun(sayHi)); // 防抖

 

Throttling:

Event triggering frequency, but only once within n seconds, the execution frequency diluted throttling function

Solution: You have to determine whether there is a trigger event is currently awaiting execution delay function

function flowFun (Fn) { 
      the let canrun = true ; // by a closure flag stored 
      return  function () {
         IF (canrun!) return ; // at the beginning of the function determines whether the flag is true, not true to return 
        canrun = to false ; // Now set to false 
        setTimeout (() => { // external execution of the function on the incoming setTimeout in 
          fn.apply ( the this , arguments);
           // Finally setTimeout finished before the flag is set to true (key) represents the cycle time can be performed when the timer flag is not executed is always false, at the beginning of the return out. 
          canrun = to true ; 
        },500);
      };
 }
 function sayHi(e) {
      console.log(e.target.innerWidth, e.target.innerHeight);
 }
 window.addEventListener('resize',flowFun(sayHi));
 

PS: image stabilization and the role of the throttle function is to prevent multiple calls. The difference is that, suppose a user of this function has been triggered, and each trigger interval is less than a wait function, it will be called once the case where the image stabilization, and the case where the throttle function is called at regular intervals (parameter wait).

 

I welcome the attention of the public numbers, hoping to learn together and progress together with you

 

 

Reference article: 1, GitHub one day face questions

     2, interviewMap of JS

Guess you like

Origin www.cnblogs.com/lxl0419/p/10951263.html