1 // 防抖 2 function debounce(func,delay){ 3 let timer = null 4 return function(){ 5 let context = this 6 let args = arguments 7 if(timer) clearTimeout(timer) 8 timer = setTimeout(()=>{ 9 func.apply(context,args) 10 },delay) 11 } 12 } 13 // 通过setTimeout实现 节流 14 function throttle(func,delay){ 15 let timer = null 16 return function(){ 17 if(!timer){ 18 let context = this 19 let args = arguments 20 timer = setTimeout(()=>{ 21 timer = null 22 func.apply(context,args) 23 },delay||1500) 24 } 25 } 26 } 27 // 通过时间比较实现 节流 28 function throttle(func,gapTime){ 29 if(gapTime == null || gapTime == undefined){ 30 gapTime = 1500 31 } 32 let _lastTime = null 33 return function(){ 34 let _nowTime = + new Date() 35 if(_nowTime - _lastTime > gapTime || !_lastTime){ 36 func() 37 _lastTime = _nowTime 38 } 39 } 40 }