谁能给我一个简单的解释,关于节流和debounging函数之间的区别,以限制速率的目的。
在我看来,两者的作用是一样的。我查看了这两个博客来找出答案:
http://remysharp.com/2010/07/21/throttling-function-calls
http://benalman.com/projects/jquery-throttle-debounce-plugin/
谁能给我一个简单的解释,关于节流和debounging函数之间的区别,以限制速率的目的。
在我看来,两者的作用是一样的。我查看了这两个博客来找出答案:
http://remysharp.com/2010/07/21/throttling-function-calls
http://benalman.com/projects/jquery-throttle-debounce-plugin/
当前回答
防反跳:
如果函数没有在间隔内被调用,则在间隔后执行函数。
节流:
以固定的时间间隔执行函数n次。
其他回答
假设我们有一个回调函数“cb”,要在事件“E”时调用。 让“E”在1秒内被触发1000次,因此会有1000次对“cb”的调用。也就是1个电话/毫秒。为了优化,我们可以使用:
节流:节流(100ms),“cb”将 在第100毫秒,第200毫秒,第300毫秒,…1000 ms)。也就是1次呼叫/100毫秒。这里对“cb”的1000次调用优化为10次调用。 debounning:当debounning为(100ms)时,“cb”只会在[1100秒]被调用一次。这是发生在第1000毫秒的最后一次触发“E”后的100毫秒。这里对“cb”的1000次调用优化为1次调用。
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()
debounging和Throttling是从一系列事件中选择目标以达到减少目标的目的。它们都需要一段时间作为参数,例如:x ms,以及后面/前面的变量来定义如何选择。
消除抖动
当x毫秒后没有其他事件发生时,选择事件
"--->": timeline "o": event "|===|": period (x=5)
--oo-o-----ooo-o----o-oo--oo-----o-o-ooo------> events
|===| |===| |===| |===|
||===| ||===| | |===| | |===|
| |===| | |===| | |===| | |===|
| | | |===|| |===| | |===|
| | | || |===| | |===|
---------o---------o-----------o-----------o--> selected events (trailing)
--o--------o--------o------------o------------> selected events (leading)
节流
当有事件发生时,每x毫秒选择一个事件
"--->": timeline "o": event "|===|": period (x=5)
--oo-o-----ooo-o----o-oo--oo-----o-o-ooo------> events
|===| |===| |===| |===| |===||===|
------o--------o--------o-----o------o----o---> selected events (trailing)
--o--------o--------o-----o------o----o-------> selected events (leading)
lodash库建议以下文章https://css-tricks.com/debouncing-throttling-explained-examples/详细解释Debounce和Throttle之间的区别及其起源
据我所知,简单来说 节流-类似于调用setInterval(回调)的特定次数,即在事件发生的时间内调用同一函数的特定次数 和. . deboundation -类似于调用setTImeout(callbackForApi)或在事件发生后经过一定时间后调用函数。 这个链接很有用 https://css-tricks.com/the-difference-between-throttling-and-debouncing/