# 前端技术(一)# 一、防抖(debounce)概念:当持续触发事件时,一定时间段没有触发事件,事件处理函数才会触发一次,如果在设定的事件到来之时触发事件,就会重新延时 (重新计算时间)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 function debounce (func,wait ){ let timer=null ;return function ( ){ let context=this ;let args=arguments ;if (timer)clearTimeout (timer);timer=setTimeout (()=> { func.apply (context,args) },wait) } }
# 二、节流(throttle)概念:当持续出发事件时,保证在一段时间内事件处理函数只触发一次。
# 第一种方法(时间戳)
1 2 3 4 5 6 7 8 9 10 11 12 13 function throttle ( ){let oldTimeDate.now ();return function ( ){ let args=arguments ;let context=this ;let newTime=Date .now ();if (newTime-oldTime>wait){ func.apply (context,args) } } }
# 第二种方法(定时器)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 function throttle ( ){let timer=null ;return function ( ){ let args=arguments ;let context=this ;if (!timer){ timer=setTimeout ( function ( ){ timer=0 ; func.apply (context,args); }, wait ) } } }