第一次会直接运行的节流代码
function throttle(fn, interval) {
// lastTime 是上一次开始的时间
let lastTime = 0;
const _throttle = function(...args) {
const nowTime = new Date().getTime(); //时间戳 一开始的时间
// interval 调用函数传入的时间
// 使用当前触发的时间 和 之前的时间间隔 以及上一次开始的的时间, 计算出还剩余多长时间会去触发我们的函数
const remainTime = interval - (nowTime - lastTime)
if (remainTime <= 0) {
fn.apply(this, args)
lastTime = nowTime;
}
}
return _throttle;
}
第一次可以控制是否执行的节流代码和最后一次是否执行
function throttle(
fn,
interval,
options = {
leading: true, // 第一次是否执行
trailing: false, // 最后一次是否执行
}
) {
const {
leading,
trailing
} = options;
let lastTime = 0;
let timer = null;
const _throttle = function(...args) {
const nowTime = new Date().getTime();
if (!lastTime && !leading) lastTime = nowTime;
const remainTime = interval - (nowTime - lastTime);
if (remainTime <= 0) {
if (timer) {
clearTimeout(timer);
timer = null;
}
fn.apply(this, args);
lastTime = nowTime;
return;
}
if (trailing && !timer) {
timer = setTimeout(() => {
timer = null;
lastTime = !leading ? 0 : new Date().getTime();
fn.apply(this, args);
}, remainTime)
}
};
return _throttle;
}