JavaScript 防抖(debounce)和节流(throttle)

Posted 荣光无限

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaScript 防抖(debounce)和节流(throttle)相关的知识,希望对你有一定的参考价值。

防抖函数

/**
 *
 * @param {*} fn :callback function
 * @param {*} duration :duration time,default wait time 0.8 秒
 * @demo in vue methods:
 *      handleEvent: _debounce(function(){
 *        do something
 *      },time)
 */
export const _debounce = (fn, duration = 800) => {
  // create timer
  let timer = null
  return function () {
    // reset once call
    clearTimeout(timer)
    // create a new timer to make sure call after define time
    timer = setTimeout(() => {
      // execute callbak, the 2nd params is fn‘s arguments
      fn.apply(this, arguments)
    }, duration)
  }
}

节流函数

/**
 * @param {*} fn: callback function
 * @param {*} duration : duration time,default wait time 1 sec
 * @demo in vue methods:
 *      handleEvent: _throttle(function(){
 *        do something
 *      },time)
 */
export const _throttle = (fn, duration = 1000) => {
  let canRun = true
  return function () {
    if (!canRun) return
    canRun = false
    // execute callbak, the 2nd params is fn‘s arguments
    fn.apply(this, arguments)
    setTimeout(() => {
      canRun = true
    }, duration)
  }
}

以上是关于JavaScript 防抖(debounce)和节流(throttle)的主要内容,如果未能解决你的问题,请参考以下文章

javascript函数的节流[throttle]与防抖[debounce]

javascript防抖(Debouncing)和节流阀(Throttling)

javascript防抖(Debouncing)和节流阀(Throttling)

JavaScript 高级系列之节流 [throttle] 与防抖 [debounce]

javascript的防抖和节流

javascript的防抖和节流深入理解