JS 节流和防抖

48 阅读1分钟

节流

const throttle = (f,time) => {
  let timer = null
  renturn(...args) =>{
    if(timer){return}
    f(...args)
    timer = serTimeout(() =>{
      timer = null
    },time)
  }
}

const f = throttle (()=>{console.log('hi')},1000) 
f() // 打印 hi
f() // 冷却中
  • 使用场景:防止用户频繁点击按钮

防抖

const debounce = (f,time) => {
  let timer = null
  return (...args) => {
    if(timer !== null){
      clearTimeout(timer)
    }
    timer = serTimeout(() => {
    f.call(undefined, ...args)
    timer = null
    }, time)
  }
}

const tp = debounce(f)
  • 使用场景:用户频繁做拖动操作时,在拖动停止后再实现效果