函數節流(throttle)和防抖(debounce)

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

  • 對用戶輸入的驗證,不在輸入過程當中就處理,中止輸入後進行驗證足以;
  • 提交ajax時,不但願1s中內大量的請求被重複發送。

節流:get

  • 對用戶輸入的驗證,不想中止輸入再進行驗證,而是每n秒進行驗證;
  • 對於鼠標滾動、window.resize進行節流控制。
相關文章
相關標籤/搜索