2020-03-12
描述
创建一个受限制的函数,每 wait 毫秒最多只能调用提供的函数一次。
提示
- 使用
setTimeout()和clearTimeout()来限制给定的方法fn - 使用
Function.prototype.apply()将this上下文应用到受限函数中,并提供其必要的arguments - 使用
Date.now()跟踪上一次调用受限函数的时间 - 第二个参数
wait用于设置受限函数每次执行的时间间隔,默认值为 0
代码
const throttle = (fn, wait) => {
let inThrottle, lastFn, lastTime;
return function() {
const context = this,
args = arguments;
if (!inThrottle) {
fn.apply(context, args);
lastTime = Date.now();
inThrottle = true;
} else {
clearTimeout(lastFn);
lastFn = setTimeout(function() {
if (Date.now() - lastTime >= wait) {
fn.apply(context, args);
lastTime = Date.now();
}
}, Math.max(wait - (Date.now() - lastTime), 0));
}
};
};
示例
当窗口拖动时,每 250 毫秒内只打印一次窗口的尺寸:
window.addEventListener(
'resize',
throttle(function(evt) {
console.log(window.innerWidth);
console.log(window.innerHeight);
}, 250)
);
ME!
链滴