防抖截流

290 阅读1分钟

防抖函数

  • 定义:当持续触发事件,一定时间内没有再触发事件,事件处理函数才会执行一次,如果设定的时间到来之前,又一次触发了事件,就重新开始延时
function debounce (fn, delay = 1000) {
  let timer = null
  return () => {
    if (timer) clearTimeout(timer)
    timer = setTimeout(fn, delay)
  }
}

截流函数

  • 定义:当持续触发事件的时候,保证一段时间内,只调用一次处理函数,一段时间内,只做一件事情
 function throttle(cb, wait) {
    let timer;
    return function () {
        if (!timer) {
            timer = setTimeout(function () {
                cb()
                timer = null
            }, wait)
        }
    }
 }