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

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

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

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


当前回答

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

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...

其他回答

简单来说:

节流将延迟执行函数。它将减少多次触发事件的通知。 deboundation将一系列对函数的连续调用合并为对该函数的单个调用。它确保为多次触发的事件发出一个通知。

你可以直观地看到其中的区别

如果你有一个函数被调用了很多次——例如当一个调整大小或鼠标移动事件发生时,它可以被调用很多次。如果您不想要这种行为,您可以Throttle它,以便定期调用该函数。deboning将意味着它在一系列事件的结束(或开始)时被调用。

油门(1秒):你好,我是机器人。只要你一直打我,我就会继续和你说话,但每次一秒后。如果你在一秒之前ping我的回复,我仍然会在1秒的间隔内回复你。换句话说,我就是喜欢隔一定的时间间隔回复。

弹跳(1秒):嗨,我是那个^^机器人的表弟。只要你一直ping我,我就会保持沉默,因为我喜欢在你最后一次ping我一秒钟后才回复。我不知道,是因为我的态度有问题还是因为我不喜欢打断别人。换句话说,如果您在上次调用后的1秒内一直向我请求回复,您将永远不会得到回复。是的是的…去吧!说我粗鲁就好。


节流阀(10分钟):我是一台伐木机。我将系统日志发送到我们的后端服务器,每隔10分钟。

反弹(10秒):嗨,我不是那台伐木机的表亲。(在这个想象的世界中,并不是每个脱锁器都与节流器有关)。我在附近一家餐馆当服务员。我应该让你知道,只要你一直在你的订单中添加东西,我就不会去厨房执行你的订单。只有在您上次修改订单后10秒后,我才会认为您已经完成了订单。到那时我才会去厨房执行您点的菜。


酷演示:https://css-tricks.com/debouncing-throttling-explained-examples/

服务员类比的功劳:https://codeburst.io/throttling-and-debouncing-in-javascript-b01cad5c8edf

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()

防反跳:

如果函数没有在间隔内被调用,则在间隔后执行函数。

节流:

以固定的时间间隔执行函数n次。

Throtle只是debounce的包装器,它使debounce在一段时间内调用传递的函数,如果debounce在一段时间内延迟函数调用,该时间大于Throtle中指定的时间。