>> 项目中经常会用到防抖和节流,怎么实现
<< 防抖:顾名思义就是防止你手抖,如果你一点在一个按钮上点还用了防抖函数,那么只有在你手不抖的时候才执行。
节流:顾名思义节约流量,本来1秒要请求10次,现在使用了节流函数,限制请求5次节约流量。
// 下面实现了一个按钮点击的防抖节流函数,只在固定的时间间隔运行。还可以配置函数是否立刻执行和最后一次防抖过的函数是否执行。
<button id="but">2</button>
<script>
const Throttle = function (
func,
wait = 1000,
options = {
leading: true,
trailing: true,
}
) {
let timeout;
let previous = 0;
console.log(this);
const later = (that, arg) => {
previous = !options.leading ? 0 : new Date().getTime();
timeout = null;
func.call(that, ...arg);
};
return function () {
const now = new Date().getTime();
if (!previous && !options.leading) previous = now;
// 剩余的时间
const remaining = wait - (now - previous);
// 剩余时间小于等于0 或 大于节流时间 立刻执行
// options.leading是true时第一次调用是0
console.log(remaining);
if (remaining <= 0 || remaining > wait) {
timeout && clearTimeout(timeout);
timeout = null;
previous = now;
func.call(this, ...arguments);
return;
}
if (!timeout && options.trailing) {
timeout = setTimeout(() => later(this, arguments), remaining);
}
};
};
let a = 0;
const add = function () {
a++;
// 指向全部正确
console.log(a, this, arguments);
};
let fun = new Throttle(add);
document.getElementById("but").addEventListener("click", fun);
// 使用完后
// fun = null;
</script>