WebHub icon indicating copy to clipboard operation
WebHub copied to clipboard

防抖节流相关整理

Open ckinmind opened this issue 6 years ago • 2 comments

参考资料

window.addEventListener("scroll", throttle(() => console.log("我在滚我在滚!")))

function throttle(fn, interval = 500) {
  let run = true;

  return function () {
    if (!run) return;
    run = false;
    setTimeout(() => {
      fn.apply(this, arguments);
      run = true;
    }, interval);
  };
}

ckinmind avatar Sep 09 '19 07:09 ckinmind

防抖

function debounce(fn, wait, immediate) {
    let timer = null

    return function() {
        let args = arguments
        let context = this

        if (immediate && !timer) {
            fn.apply(context, args)
        }

        if (timer) clearTimeout(timer)
        timer = setTimeout(() => {
            fn.apply(context, args)
        }, wait)
    }
}

 // 调用测试
 const actionFnc = () => console.log('触发窗口监听回调函数')
 const debouncedFn = debounce(actionFnc, 1000, true)
 window.onresize = () => {
    debouncedFn()
  }
  • 第一次调用函数,创建一个定时器,在指定的时间间隔之后运行代码
  • 当第二次调用该函数时,它会清除前一次的定时器并设置另一个
  • 如果前一个定时器已经执行过了,这个操作就没有任何意义
  • 然而,如果前一个定时器尚未执行,其实就是将其替换为一个新的定时器。目的是只有在执行函数的请求停止了一段时间之后才执行
  • 提供immediate立即执行选项,方便某些时候能够立即执行函数而不是等一段时间再执行
  • 防抖的作用是将多次高频操作优化为只在最后一次执行

ckinmind avatar Nov 12 '19 08:11 ckinmind

节流

function throttle(fn, wait, immediate) {
    let timer = null
    let callNow = immediate

    return function() {
      let args = arguments
      let context = this

      if (callNow) {
        fn.apply(context, args)
        callNow = false
      }

      if (!timer) {
        timer = setTimeout(() => {
          fn.apply(context, args)
          timer = null
        }, wait)
      }
    }
  }

  const actionFnc = () => {
    console.log('触发窗口监听回调函数')
  }
  const throttleFn = throttle(actionFnc, 2000, true)

  // 调用测试
  window.onresize = () => {
    throttleFn()
  }

  • 第一次调用,创建一个定时器,在指定的间隔之后运行代码
  • 当第二次调用函数时,会先检测上一个定时器是否已经执行且重置,如果已经执行且重置则重新设定新的定时器,如果没有则不触发任何反应
  • 提供immediate立即执行选项,方便某些时候能够立即执行函数而不是等一段时间再执行
  • 节流的作用是在控制调用的触发频率,在指定的时间内只执行一次

ckinmind avatar Nov 13 '19 06:11 ckinmind