函数throttle、debounce介绍

743 阅读1分钟
  • 背景:如监听窗口大小的改变、滚动,因为我们稍微改变一下窗口大小、鼠标滚轮稍微滚动一下,就可以调用几十次函数,事件在队列里排队等待执行,而js是单线程的,这样会阻碍其他事件的执行、造成卡顿、假死、用户体验差等问题,这就需要用到throttle、debounce来减少函数的执行次数
  1. 节流,减少事件的执行次数,
// 简易版
const throttle = (func, limit) => {
  let inThrottle
  return function() {
    const args = arguments
    const context = this
    if (!inThrottle) {
      func.apply(context, args)
      inThrottle = true
      setTimeout(() => inThrottle = false, limit)
    }
  }
}

// 可以获得最后一次的执行
const throttle = (func, limit) => {
  let lastFunc
  let lastRan
  return function() {
    const context = this
    const args = arguments
    if (!lastRan) {
      func.apply(context, args)
      lastRan = Date.now()
    } else {
      clearTimeout(lastFunc)
      lastFunc = setTimeout(function() {
        if ((Date.now() - lastRan) >= limit) {
          func.apply(context, args)
          lastRan = Date.now()
        }
      }, limit - (Date.now() - lastRan))
    }
  }
}

2.函数防抖

const debounce = (func, delay) => {
  let inDebounce
  return function() {
    const context = this
    const args = arguments
    clearTimeout(inDebounce)
    inDebounce = setTimeout(() => func.apply(context, args), delay)
  }
}

Throttling and Debouncing in JavaScript