【JS手写题】进度1/32 防抖/节流实现

40 阅读1分钟

防抖函数

/** 防抖
 * 含义:在规定的时间内,再次触发操作,会重置定时器
 * 定时器的时间结束后,才会执行操作
*/
export const debounce = (fn, delay = 300) => {
  let timer = null
  return function (...args) {
    if (timer) {
      clearInterval(timer)
    }
    timer = setTimeout(() => {
      // 执行方法
      fn.apply(this, args)
    }, delay)
  }
}

节流函数

/**
 * 节流
 * 含义:在约定的时间内,只能执行一次操作,多余的操作会被忽略
 */
export const throttle = (fn, delay = 300) => {
  let timer = null
  return function (...args) {
    if (!timer) {
      timer = setTimeout(() => {
        fn.apply(this, args)
        timer = null
      }, delay)
    }
  }
}

使用

// 防抖
window.addEventListener('resize', debounce(onResize))
// 注:记得移除事件
window.removeEventListener('resize', debounce(onResize))

// 传递参数
const test = debounce(onResize)
window.addEventListener('resize', function () {
test(11)
})  // 输出:11