谁能给我一个简单的解释,关于节流和debounging函数之间的区别,以限制速率的目的。

在我看来,两者的作用是一样的。我查看了这两个博客来找出答案:

http://remysharp.com/2010/07/21/throttling-function-calls

http://benalman.com/projects/jquery-throttle-debounce-plugin/


当前回答

debound使函数只能在最后一次调用后的一段时间后执行

function debounce(func,wait){
  let timeout
  return(...arg) =>{
    clearTimeout(timeout);
    timeout= setTimeout(()=>func.apply(this,arg),wait)
  }
}


function SayHello(){
  console.log("Jesus is saying hello!!")
}


let x = debounce(SayHello,3000)
x()

节流模式限制了在一段时间内可以调用给定事件处理程序的最大次数。它允许以指定的时间间隔周期性地调用处理程序,忽略该等待期结束之前发生的每个调用。

function throttle(callback, interval) {
  let enableCall = true;

  return (...args)=> {
    if (!enableCall) return;

    enableCall = false;
    callback.apply(this, args);
    setTimeout(() => enableCall = true, interval);
  }
}


function helloFromThrottle(){
  console.log("Jesus is saying hi!!!")
}

const foo = throttle(helloFromThrottle,5000)
foo()

其他回答

这里真正重要的是,用最简单的话说:如果你有一些连续重复一段时间的操作(如鼠标移动,或页面大小调整事件),你需要运行一些函数来响应,但你不想对每个操作都做出反应(因为这可能会损害性能),你有两个选择:

debounce - you skip all incoming actions, except the last one (the 'last one' is defined by the 'wait' time period you set for debounce function, for example, 2s - it will consider that actions flood stopped, if no actions were taken for 2s, and then it will react. This strategy is reasonable if you don't care about regular updates, you just need to react at least once. throttle - if you want to react 'on schedule', to make regular updates even if actions flood is endless, you make your function run at regular intervals (no more often, then the specified time interval), for example 2s throttling will mean that your response will be executed an once if action is taken, but no less then 2s after that. So with continuous actions flood your response will be run on 0s, 2s, 4s, 6s, 8s...

通俗地说:

debound将阻止一个函数在仍然被频繁调用时运行。debound函数只在确定不再被调用后才会运行,此时它只会运行一次。脱绳的实际例子:

如果用户“停止输入”,自动保存或验证文本字段的内容:该操作将只执行一次,在确定用户不再输入(不再按键)之后。 记录用户休息鼠标的位置:用户不再移动鼠标,因此可以记录(最后)位置。

节流只会阻止最近运行过的函数运行,不管调用频率如何。节流的实际例子:

v-sync的实现是基于节流的:从上一次绘制屏幕到现在已经过去了16ms,屏幕才会被绘制。无论调用多少次屏幕刷新功能,它最多只能每16毫秒运行一次。

lodash库建议以下文章https://css-tricks.com/debouncing-throttling-explained-examples/详细解释Debounce和Throttle之间的区别及其起源

这实际上是限制一个事件的方法。例如,如果你正在监听onclick事件,如果它是常规的,它将监听你所做的每一次点击。

如果你使用Throttle,它会在你想要监听事件的时间之间设置一个间隔,例如每秒钟监听一次点击。

Debounce的限制更大,它只会在事件开始或结束时触发自己。例如,你正在滚动,你使用Debounce,它只会在你开始和结束滚动时触发。

据我所知,简单来说 节流-类似于调用setInterval(回调)的特定次数,即在事件发生的时间内调用同一函数的特定次数 和. . deboundation -类似于调用setTImeout(callbackForApi)或在事件发生后经过一定时间后调用函数。 这个链接很有用 https://css-tricks.com/the-difference-between-throttling-and-debouncing/