1、节流和防抖ajax
咱们知道过于频繁的dom操做会致使页面卡顿甚至浏览器崩溃,节流和防抖能够用于缓解在某段时间内频繁调用函数带来的压力。浏览器
节流:在某段时间内,只容许函数执行一次,随后进入下一个执行周期app
防抖:在连续的操做以后过一段时间才会执行一次函数dom
2、函数实现函数
一、防抖debouncethis
1 function debounce(fun, delay){ 2 let timer; 3 return function(){ 4 let context = this; 5 let args = arguments; 6 clearTimeout(timer); 7 timer = setTimeout (()=>{ 8 fun.apply(context,args); 9 },delay) 10 } 11 }
二、节流throttlespa
1 function throttle(fun, delay, mustRunDelay){ 2 let timer = null 3 let start 4 return function(){ 5 let context = this 6 let args = arguments 7 let now = new Date().getTime() 8 clearTimeout(timer) 9 if(!start){ 10 start = now; 11 } 12 if(now - start >= mustRunDelay){ 13 fun.apply(context, args) 14 }else{ 15 timer = setTimeout(()=>{ 16 fun.apply(context, args) 17 },delay) 18 } 19 } 20 }
3、应用场景code
防抖:blog
节流:get