underscore.js: _.throttle(function, wait)

前端 未结 5 1075
轮回少年
轮回少年 2021-02-19 13:21

According the underscore documentation:

throttle_.throttle(function, wait)
Creates and returns a new, throttled version of the pa

5条回答
  •  孤城傲影
    2021-02-19 13:46

    The difference between throttle and debounce is described here: https://css-tricks.com/the-difference-between-throttling-and-debouncing/

    /*
    "Debouncing enforces that a function not be called again until a certain amount of time has passed without it being called. As in "execute this function only if 100 milliseconds have passed without it being called."
    "Perhaps a function is called 1,000 times in a quick burst, dispersed over 3 seconds, then stops being called. If you have debounced it at 100 milliseconds, the function will only fire once, at 3.1 seconds, once the burst is over. Each time the function is called during the burst it resets the debouncing timer."
    */
    _.debounce = (fn, delay) => {
      let timer
      return (...args) => {
        if (timer) clearTimeout(timer)
        timer = setTimeout(() => {
          fn.apply(null, args)
        }, delay)
      }
    }
    /*
    "Throttling enforces a maximum number of times a function can be called over time. As in "execute this function at most once every 100 milliseconds."
     */
    _.throttle = (fn, delay) => {
      let canCall = true
      return (...args) => {
        if (canCall) {
          fn.apply(null, args)
          canCall = false
          setTimeout(() => {
            canCall = true
          }, delay)
        }
      }
    }
    

提交回复
热议问题