JavaScript 函数节流和函数防抖

函数节流和函数防抖,两者都是优化高频率执行js代码的一种手段。

  • 函数节流

是一定时间内只执行一次。

  • 函数防抖

函数在特定的时间内不被再调用后执行

比如生活中的坐公交,就是一定时间内,如果有人陆续刷卡上车,司机就不会开车。等到没有人刷卡了,司机再开车。

函数节流代码示例:

 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()
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。