版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhaoruda/article/details/88764603
debounce 和 throttle
为什么要使用 debounce 和 throttle
在实际开发过程中会遇到这样对问题:
- 点击事件:连续点击按钮
- 鼠标事件:拖动鼠标滑动
- 实时搜索,在输入过程中不触发搜索方法
由于这样对行为会导致对应对方法被执行多次,所以如果不进行处理就会带来性能问题、页面卡顿和多次提交ajax请求等。
这时就会考虑使用debounce和throttle来解决该类问题。
这两个方法都可以解决某个方法在一定时间内多次执行对解决方案,但是两者之间又有些不同。
debounce 和 throttle的区别
debounce:
debounce(去抖动)。假设时间计数为10s,如果在10s内方法被再次调用,则重新开始计数。如果在10s内方法没
有再次调用,则会执行对应对方法。
throttle(节流)。和debounce对区别在于throttle会保证在10s内方法肯定会被执行一次。比如:第一次调用之
后5s进行第二次调用,再等5s之后进行第三次调用。虽然每次对间隔都在10s以内,但是累积时间已经到10s了,这时方法就会被调用
一次。
代码实现
debounce:
- 在闭包中维护timer
- 再次调用时清楚timer,并重新创建
function debounce(action, delay) {
let timer = null;
return function () {
const self = this;
const args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
action.apply(self, args)
}, delay);
}
}
throttle:
- 在闭包中维护timer和时间阈值
- 再次调用时清楚timer,并比较是否到达时间阈值
- 没有到达阈值则新建timer,否则调用方法执行
function throttle(action, delay) {
let timer = null;
let startTime = null;
return function () {
const self = this;
const args = arguments;
const currentTime = Date.now();
clearTimeout(timer);
if(!startTime){
startTime = currentTime;
}
if (currentTime - startTime >= delay) {
action.apply(self, args);
startTime = currentTime;
} else {
timer = setTimeout(function () {
action.apply(self, args)
}, delay);
}
}
}