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