Appearance
截流 throttle
定义:在指定时间间隔内,函数最多只执行一次
应用场景
- 无限滚动加载更多内容
- 点击按钮的限制 (抢购)
简单实现
js
function throttle(fn, delay) {
// 1. 上一次执行的时间
let lastTime = 0;
return function (...args) {
// 2. 每次调用这个函数,获取最新的时间
const now = Date.now();
// 3. 当前时间 - 上一次的时间 >= 应等待的时间
if (now - lastTime >= delay) {
// 4. 执行传递的函数,并绑定 this
const result = fn.apply(this, args);
// 5. 上一次执行的时间 为当前时间
lastTime = now;
// 6. 返回返回值
return result;
}
};
}
const throttled = throttle(function () {
console.log("hi throttle");
}, 3000);
setInterval(() => {
throttled();
}, 500);Leading & Trailing
- 手动控制 头部 / 尾部 的执行
js
function throttle(fn, wait, options = {}) {
// 1. 定义 options
const { leading = true, trailing = true } = options;
// 2. 上一次执行 fn 的时间戳
let lastTime = 0;
// 3. 尾部的定时器变量
let timer = null;
return function (...args) {
// 4. 执行截流后的函数,每次拿到最新的时间戳
const now = Date.now();
// 5. 是否达到了间隔时间
if (now - lastTime >= wait) {
// 6. 头部是否执行
if (leading) {
fn.apply(this, args);
}
lastTime = now;
}
// 7. 尾部需要执行 & timer 没值的情况 & 不是头部需要执行
if (trailing && !timer && !leading) {
// 8. 开启定时器
timer = setTimeout(() => {
// 9. 执行函数
fn.apply(this, args);
// 10. 清空定时器
timer = null;
}, wait);
}
};
}