好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

typescript写防抖节流

注意:在javascript 中,我们一般直接使用函数利用闭包封装,这里会涉及this ,在typescript 中如果还是用函数写,this就会受到限制,无法通过编译的,所以可以使用class解决

防抖:在规定时间内重复操作一个事件只会执行一次,在时间段内会重新计算执行开始时间,常用与滚动事件,操作请求后台接口(防止频繁操作)

节流:连续触发事件,n秒内只执行一次,节流会降低执行函数频率,可以用在并发的操作

 

  1   export class Debounced {
   2  
  3       /*  *
   4        * 
   5        * @param fn 要执行的函数
   6        * @param awit  时间
   7        * @param immediate 是否在触发事件后 在时间段n开始,立即执行,否则是时间段n结束,才执行
   8        */ 
  9      static use(fn:Function,awit:number=1000,immediate: boolean = false  ){
  10          let timer:NodeJS.Timeout| null 
 11           return  (...args:any)=> {
  12               if  (timer) clearInterval(timer)
  13               if  (immediate){
  14                   if (!timer) fn.apply( this  ,args);
  15                  timer = setTimeout( function (){ //  n 秒内 多次触发事件,重新计算.timeer  
 16                      timer =  null ; //  n 秒内没有触发事件 timeer 设置为null,保证了n 秒后能重新触发事件 flag = true = !timmer   
 17                   },awit)
  18              } else  {
  19                  timer = setTimeout(()=>{ fn.apply( this  ,args)},awit)
  20               }
  21           }
  22       }
  23  
 24  }

 

 export class Throttle{
      /*  *
     * 
     * @param fn 
     * @param awit 
     * @param immediate true 是启用时间戳版,false 是启用定时器版,作用一样
       */  
    static use(fn:Function,awit:number =1000,immediate: boolean = true  ){
          //  时间戳 
         if  (immediate){
            let prevTime  = 0 ;
              return  (...args:any)=> {
                let nowTime  =  Date.now();
                  if (nowTime-prevTime>= awit){
                    fn.apply(  this  ,args)
                    prevTime = nowTime
                }
            }
        }  else  {
              //  定时器 
            let timer: NodeJS.Timeout| null  ;
              return  (...args:any)=> {
                  if (! timer){
                    fn.apply(  this  ,args)
                    timer  = setTimeout(() =>  {
                        timer && clearTimeout(timer)
                        timer =  null  
                    }, awit);
                }
               
            }
        }

        
    }
    

} 

 

查看更多关于typescript写防抖节流的详细内容...

  阅读:58次