函数防抖和函数节流

343 阅读1分钟

函数防抖

函数防抖就好比调了一个半小时后响起的闹钟,当摁下按钮开始计时,在半小时内再次摁下按钮就又从头计时,直到半小时期间内没有再次摁按钮,半小时后闹钟才会响起。 示例代码如下:

let timer
function debounce(fn,delay){
  if(timer){clearTimeout(timer)}
  timer=setTimeout(function(){
      fn()
  },delay)
}
document.onclick=function(){
  debounce(()=>console.log('防抖了'),3000)
}

应用场景:拖动窗口,改变窗口尺寸大小时。

函数节流

就好比游戏技能的冷却CD,当点击触发技能后,一段时间内就不能再次触发,直到冷却时间后才可刷新技能。 示例代码如下:

let initial=0
function throttle(fn,delay){
  let now=new Date()  
  if(now-initial>delay){
      fn()
      inite=now
  }
}
document.onclick=function(){
  throttle(()=>console.log(`节流了${initial}`),3000)
}

应用场景:表单提交时,避免频繁操作。