-
Notifications
You must be signed in to change notification settings - Fork 8
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Javascript 的 Debounce 和 Throttle 的原理及实现 #7
Comments
最近在学习debouce的实现原理,lodash的源码maxWait的部分还是没太看懂,博主这篇文章也很棒,学习~ |
讲的非常清晰。 |
楼主,你的 |
楼主,有个问题想问一下。 // 如果距离上次执行 fn 函数的时间小于 threshhold,那么就放弃
// 执行 fn,并重新计时
if (last && now < last + threshhold) {
clearTimeout(timer)
// 保证在当前时间区间结束后,再执行一次 fn
timer = setTimeout(function () {
last = now
fn.apply(context, args)
}, threshhold)
// 在时间区间的最开始和到达指定间隔的时候执行一次 fn
} 按照我的理解, if (timer) {
return;
}
timer = setTimeout(function() {
clearTimeout(timer);
timer = null;
fn.apply(context, args);
}, threshold); |
我觉得在延迟执行时,应该计算剩余时间,在剩余时间后执行。这样能实现如果频繁调用的话,每个 threshhold 时间点都会执行一次。 否则如果每次都延迟 threshhold 时间执行,有可能会出现两次执行间隔接近 2*threshhold,延迟太久了。 function throttle(fn, threshhold) {
let timer, last
return function() {
const context = this
const args = arguments
const now = +new Date()
// 如果之前有执行过并且距离上次执行时间小于阈值,则延迟剩余时间后再执行
// 保证执行间隔大于阈值
const remaining = last ? last + threshhold - now : 0
if (remaining > 0) {
clearTimeout(timer)
timer = setTimeout(() => {
last = +new Date()
fn.apply(context, args)
}, remaining)
}
// 第一次调用会执行,从上次执行开始超过阈值也会执行
else {
last = +new Date()
fn.apply(context, args)
}
}
} |
@Jancat 在setTimeout中使用了箭头函数的话,是不是应该不用保存context上下文? |
@Wangszzju 还是需要保存 context 上下文的。 setTimout 中的箭头函数中如果使用到 如果不使用 apply(),则 |
@Jancat 用箭头函数不用保存 this 为 context. 他执行的时候的 this 值就是创建它的环境的 this, 跟它在什么环境下执行无关 |
@lishengzxc 你的 throttle 实现是不是有不妥当的地方. 0ms : 第一次点击. else 分支. 马上发射一次子弹; 应该不管 if/else, 都要 clearTimeout function throttle(fn, threshhold = 250) {
let last
let timer
return function inner(...args) {
const now = Date.now()
clearTimeout(timer) // 每次触发都清除 timer
if (last && now < last + threshhold) {
timer = setTimeout(() => {
last = Date.now()
fn.apply(this, args) // 箭头函数的 this 为创建它的环境的 this, 即 inner 函数的 this
}, threshhold)
} else {
last = now
fn.apply(this, args)
}
}
} |
作者你好,我把你的debounce实现做了下修改,修改如下: function debounce(func, delay) {
// 保存函数调用时的上下文和参数,传递给 func
const context = this
const args = arguments
// 返回一个函数,这个函数会在一个时间区间结束后的 delay 毫秒时执行 func 函数
return () => {
// 每次这个返回的函数被调用,就清除定时器,以保证不执行 func
if (window.GLOBAL_TIMER) clearTimeout(window.GLOBAL_TIMER)
// 当返回的函数被最后一次调用后(也就是用户停止了某个连续的操作),再过 delay 毫秒就执行 func
window.GLOBAL_TIMER = setTimeout(() => func.apply(context, args), delay)
}
} |
问题在于debounce函数中clearTimeout(timer)语句,其实并没有实质作用。 因为timer变量被保存在debounce方法执行后返回的防抖函数的作用域中,清除的只是当前作用域内的timer变量,重复执行debounce函数,会产生多个防抖函数及其作用域,每个作用域中的timer变量都是不相干的,所以会导致防抖失效。 我稍作修改,这样就正常的实现了防抖功能,以上只是我的个人见解,还请您指教哈哈。 |
兄弟你这个 |
@WanderHuang 是的,您没指出来我都没注意这个问题,感谢指正! |
总感觉哪里不对- - |
好的,谢谢啦 |
@icymind 你好,我想问下, 传入的 fn 的 this 变化时, 你的代码片段是不是不适用呢? |
我觉得间隔没有问题吧,问题在于定时器没做更新,不能更新 args,节流虽然是节流了,但是拿到的不是最新的参数 |
分析
_
的.debounce
和.throttle
DOM 上有些事件是会频繁触发的,比如
mouseover
、scroll
、resize
...。以前有个需求,是做一个图表,是用canvas
画的,最初,如果图表画完,用户拖拽浏览器窗口,改变浏览器大小的话,图表并不会自适应的变化,所以就需要监听resize
事件,每当窗口大小变化后,再重新绘制。但是resize
是频繁触发的,这就导致了页面的明显的卡顿,因为每次resize
后的回调要执行大量的计算。当时比较急,遇到这个问题以后,直接就查了
.debounce
和.throttle
,就直接用了lodash
。现在回过头了,看下源码,看看它的实现。Debounce
英文释义:
我们希望开关只捕获到那次最后的精准的状态切换。在 Javascript 中,那些 DOM 频繁触发的事件,我们想在某个时间点上去执行我们的回调,而不是每次事件每次触发,我们就执行该回调。有点啰嗦,再简单一点的说,我们希望多次触发的相同事件的触发合并为一次触发(其实还是触发了好多次,只是我们只关注那一次)。
所以,在 Javascript 中,我们就希望频繁事件的回调函数在某段连续时间内,在事件触发后只执行一次。
拿
resize
事件为例,在 2s 内的该事件会被触发多次(具体几次未知,不同浏览器并不一样)。我们需要对resize
的回调函数做 Debounce 100ms 化,这样resize
的回调会在 2.1s 后触发,之前 2s 以内的resize
我就无视了。我们先自己实现一个
将 Debounce 化后的闭包函数作为频繁触发的事件的回调,其实还是频繁执行的,只不过,返回的闭包函数内部通过
clearTimeout()
,让真正需要执行的回调函数不执行了,只有在连续时间内,不在触发频繁事件后的delay
秒后,执行真正的回调。Demo
http://lishengzxc.github.io/bblog/Debounce.html
再鼠标不移动后的 1000ms 后,执行了真正的回调,打印了当前时间戳。
比较合理的应用场景还有,在一个表单的输入框中(包括多行文本输入框),想当用户停止输入后,再
ajax
:_
的.debounce()
分析先看看
underscore
的。它的
debounce
还接受第三个参数immediate
,这个参数是用来配置回调函数是在一个时间区间的最开始执行(immediate
为true
),还是最后执行(immediate
为false
),如果immediate
为true
,意味着是一个同步的回调,可以传递返回值。关键的地方是,单独拿出了一个
later
函数通过控制timer
来觉得连续的时间除一开始后,是不是要执行回调。loadsh
的debounce
,接受更多的配置:[options.leading=false] (boolean)
: Specify invoking on the leading edge of the timeout.[options.maxWait] (number)
: The maximum time func is allowed to be delayed before it’s invoked.[options.trailing=true] (boolean)
: Specify invoking on the trailing edge of the timeout.lodash
的debounce
源代码leading=true
等效于underscore
的immediate=true
。trailing
则正好相反。maxWait
设置了超时时间,在规定的超时间后,一定调用回调。(通过内部设置了两个setTimeout
,一个用来完成基础功能,让回调只执行一次,还有一个用来控制超时)Throttle
英文释义:
throttle
就是设置固定的函数执行速率,从而降低频繁事件回调的执行次数。前面提到的canvas
绘制好的图表后,用户改变窗口大小后,重新绘制图表,就很适合使用throttle
。最近在写一个 Tank 游戏,用户可以非常快的点击开火,但是我们需要通过 Throttle,来降低一些开火的频率。我们先自己实现一个
代码中,比较关键的部分是最后部分的
if .. else ..
,每次回调执行以后,需要保存执行的函数的时间戳,为了计算以后的事件触发回调时与之前执行回调函数的时间戳的间隔,从而根据间隔判断要不要执行回调。_
的.throttle()
分析直接看
underscore
的。因为lodash
没有对其再进行包装。其中
previous
相当于自己实现代码中的last
。它还接受leading
和trailing
来控制真正回调触发的时机,这和lodash
的_.debounce
差不太多。最后
这里有一个可视化分析页面:http://demo.nimius.net/debounce_throttle/,大家可以点开看看。
The text was updated successfully, but these errors were encountered: