防抖
- 概念:在某段时间间隔内,频繁触发一个函数时,只执行最后一次的触发。
- 代码实现:
const debounce = function (fn, interval) {
let timer,
firstTime = true,
__self = fn;
return function () {
let args = arguments,
__me = this;
if (firstTime) {
__self.apply(__me, args);
return (firstTime = false);
}
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
clearTimeout(timer);
__self.apply(__me, args);
}, interval || 500);
};
};
复制代码
节流
- 概念:在某段时间间隔内,频繁触发一个函数时,在相同的时间间隔内只执行一次触发。
- 代码实现:
const throttle = function (fn, interval) {
let timer,
firstTime = true,
__self = fn;
return function () {
let args = arguments,
__me = this;
if (firstTime) {
__self.apply(__me, args);
return (firstTime = false);
console.log(123);
}
if (timer) {
return false;
}
timer = setTimeout(() => {
clearTimeout(timer);
timer = null;
__self.apply(__me, args);
}, interval || 500);
};
};
复制代码