9

I am a bit uncertain with the concepts of throttle and debounce functions.

As I get it:

we debounce a function that should be called after a certain event has happened. It is used in events like drag, keyup, etc. with the purpose of not firing all the time the event gets fired but instead when the series of events is done. Typically after a whole word has been typed, or a drag or resize sequence has ended.

we throttle a function that should fire while a series of events is happening, but when we want to control the amount of times it gets called. Like in a drag movement we want the function to be called only every x pixels of distance, or only every 100ms, and not every time the event is fired. So the throttle function is called while the series of events is happening, just fewer times.

Question:

is this a correct perception of what these functions are and their purpose? are there other features that distinguish them?

4

3 回答 3

3

是的,这是对差异的一个很好的概括。

但是,您可能想强调这些方法实际上并没有改变它们被调用的函数。他们只是创建一个新函数(具有一个身份,速率限制行为绑定到该函数),该函数可以根据需要经常调用,并在内部将调用中继到去抖动或节流函数。

于 2015-05-13T18:46:14.633 回答
3

简而言之:

节流阀被设计为在恒定调用期间以一定的间隔调用函数。比如:window.scroll。 debounce被设计为在特定时间内只调用一次函数。不管它调用了多少次。喜欢:提交按钮点击。这是示例:

//http://jsfiddle.net/1dr00xbn/

你可以看到区别。

于 2015-06-04T10:27:36.850 回答
1

正如我的 TL 今天指出的,值得一提的是,在 lodash 中这两个函数的流行实现中:

油门功能其实只是debounce的具体配置:

function throttle(func, wait, options) {
  let leading = true
  let trailing = true

  if (typeof func != 'function') {
    throw new TypeError('Expected a function')
  }
  if (isObject(options)) {
    leading = 'leading' in options ? !!options.leading : leading
    trailing = 'trailing' in options ? !!options.trailing : trailing
  }
  return debounce(func, wait, {
    'leading': leading,
    'maxWait': wait,
    'trailing': trailing
  })
}
于 2018-08-31T14:56:02.760 回答