函数的节流和防抖

303 阅读1分钟

函数防抖和函数节流都是防止某一时间频繁触发,但是这两兄弟之间的原理却不一样。

函数节流是间隔时间执行,而函数防抖是某一段时间内只执行一次,

节流

 // 函数节流就是fps游戏的射速,就算一直按着鼠标射击,也只会在规定射速内射出子弹。
 function throttle(fn, delay){
     let canUse = true
     return function(){
         if(canUse){
             fn.apply(this, arguments)
             canUse = false
             setTimeout(()=>canUse = true, delay)
         }
     }
 }

 const throttled = throttle(()=>console.log('hi'))
 throttled()
 throttled()

防抖

// 函数防抖就是法师发技能的时候要读条,技能读条没完再按技能就会重新读条。
 function debounce(fn, delay){
     let timerId = null
     return function(){
         const context = this
         if(timerId){window.clearTimeout(timerId)}
         timerId = setTimeout(()=>{
             fn.apply(context, arguments)
             timerId = null
         },delay)
     }
 }
 const debounced = debounce(()=>console.log('hi'))
 debounced()
 debounced()