js achieve image stabilization, throttle

Anti-shake function.

  Several operations will be combined into a single operation. Set a timer, trigger delay time specified in the function, but if the delay time is triggered again, it will cancel the timer before. Thus, only the last operation can be triggered. code show as below:

function debounce(fn,wait){
     let timer=null;
     return function(){
          let args=arguments,that=this;
          timer&&clearTimeout(timer);
          timer=setTimeout(function(){fn.apply(that,args)},wait)
     }        
} 

Throttling function.

  Within a certain period of time one-shot function. And trigger a start, the end of the trigger once. code show as below:

function throttle(fun, delay){
  let timer = null;
  let startTime = Date.now();
  return function(){
    let curTime = Date.now();
    let remain = delay - (curTime - startTime);
    let that = this;
    let args = arguments;
    clearTimeout(timer);
    if(remain <= 0){
      fun.apply(that,args);
      startTime = Date.now();
    }else{
      timer = setTimeout(fun, remain);
    }
  }
}

 

Guess you like

Origin www.cnblogs.com/wjgoblin/p/10950886.html