LLwanran / front_end_studying

前端知识要点
https://llwanran.github.io/front_end_studying/
2 stars 1 forks source link

实现防抖函数(debounce)和节流函数(throttle) #45

Open LLwanran opened 5 years ago

LLwanran commented 5 years ago

防抖函数原理:在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时。

export default function (fn, wait = 250, immediate) {
  let timeout

  function debounced (...args) {
    const later = () => {
      timeout = null
      if (!immediate) {
        fn.apply(this, args)
      }
    }

    clearTimeout(timeout)
    if (immediate && !timeout) {
      fn.apply(this, args)
    }
    timeout = setTimeout(later, wait)
  }

  debounced.cancel = () => {
    clearTimeout(timeout)
  }

  return debounced
}

适用场景:

生存环境请用lodash.debounce

节流函数原理:规定在一个单位时间内,只能触发一次函数。如果这个单位时间内触发多次函数,只有一次生效。

export default function (fn, limit = 250) {
  let wait = false
  let result

  return function (...args) {
    if (wait) {
      return result
    }

    wait = true
    result = fn.apply(this, args)
    setTimeout(() => {
      wait = false
    }, limit)
    return result
  }
}

适用场景: