手写函数三:实现防抖节流

125 阅读1分钟

防抖(debounce)

防抖(debounce)是什么?

当持续触发事件时,一定时间段内没有再触发事件,事件处理函数才会执行一次,如果设定的时间到来之前,又一次触发了事件,就重新开始延时。

使用场景:

输入框,scroll以及resize事件

实现

const debounce = (fn, wait) => {
    let time = null
    return (...args) => {
        if (time)
            clearInterval(time)
        time = setTimeout(() => {
            fn.apply(this, args)
        }, wait)
    }
}

节流(throttle)

节流(throttle)是什么?

当持续触发事件时,保证一定时间段内只调用一次事件处理函数

使用场景:

mousedown事件

实现

const throttle = (fn, wait) => {
    let flag = true
    return (...args) => {
        if (!flag) return
        flag = false
        setTimeout(() => {
            fn.apply(this, args)
            flag = true
        }, wait)
    }
}

立即执行

function debounce(func, wait, immediate = false) {
  let timeout;
  return function () {
    const context = this;
    const args = arguments;
    if (timeout) clearTimeout(timeout);
    if (immediate) {
      const callNow = !timeout;
      timeout = setTimeout(() => {
        timeout = null;
      }, wait);
      if (callNow) func.apply(context, args);
    } else {
      timeout = setTimeout(() => {
        func.apply(context, args);
      }, wait);
    }
  };
}