debounce & throttle

319 阅读1分钟

背景

在用户交互场景,用户行为触发频繁,需要根据实际场景进行行为合并

debounce去抖

const myFn = debounce(fn, waitTime)

在事件fn触发后,在waitTime的计时完成后执行fn;如果计时期间fn再次触发,重置waitTime计时,最终执行最后一次fn调用

应用场景

监听用户输入框输入,触发请求

代码实现

function debounce(fn, waitTime = 0) {
 let timer = null
 return function() {
  if (timer) clearTimeout(timer)
  timer = setTimeout(() => {
   fn.apply(thisarguments)
   timer = null
  }, waitTime)
 }
}

throttle节流

const myFn = throttle(fn, waitTime)

在事件fn首次触发后,立即执行,在waitTime的计时内再次触发fn,将在计时完成后执行最后一次fn调用

应用场景

监听浏览器onScroll事件

代码实现

function throttle(fn, waitTime = 0) {
 let timer = null, lastThis = null, lastArguments = null
 return function() {
  if (!timer) {
   fn.apply(thisarguments)
   timer = setTimeout(() => {
    if (lastThis) {
     fn.apply(lastThis, lastArguments)  
    }
    lastThis = null
    lastArguments = null
    timer = null
   }, waitTime)
  } else {
   lastThis = this   
   lastArguments = arguments
  }
 }
}

最后

github

在线demo