节流和防抖

 

1. 防抖debounce

防抖:debounce,不会立马执行的,触发后,过一段时间执行,如果在时间到达之前又触发了,那重新等待
常用于比如我们下拉框关键字输入远程搜索,如果不做防抖,那用户一边输入关键字,搜索的请求会立马发起,在完整输入一串关键字的过程中,可能会触发多次查询,但这是无意义的,浪费资源。
 1 function debounce(fn,wait){
 2   let timer;
 3   return function(){
 4       // 每次触发都清空之前的,然后重新等待执行
 5       if(timer){
 6           clearTimeout(timer)
 7       }
 8       let _this = this;
 9       let args = arguments;
10       timer = setTimeout(()=>{
11           fn.apply(_this,args)
12     },wait)    
13   }    
14 }    
15 // 以拖动窗口为例,一直拖动窗口,不会一直打印resize,只有在你停下来后,等待2s才会打印
16 window.onresize = debounce(()=>{console.log('resize')},2000)

2. 节流throttle

节流:  throttle,触发后,过一段时间执行,即使在等待过程中,再次触发,会忽略掉
 1 function throttle(fn,wait){
 2      let timer;
 3      return function(...args){
 4         
 5          if(timer){
 6              return
 7          }
 8          timer = setTimeout(()=>{
 9             fn(...args)
10             clearTimeout(timer)
11          },wait)
12      }
13  }    

 

posted @ 2024-04-15 15:42  蛙仔  阅读(6)  评论(0编辑  收藏  举报