前面的文章(https://blog.terrynow.com/2020/12/23/javascript-debounce/)里是介绍的限制频率,延时去抖动,即:N秒内,仅允许最后一次执行,也就是说理论上用户一直不停的操作下去,永远也得不到执行,现在的要求是,即使这种情况下,也要间隔一定的时间运行(即限制频率调用)
这个要比之前的简单实现,因为只要设定一个状态,或者设定一个时间戳变量,在setTimeout函数里判断下就可以了
// 方式1
function throttle(fn, delay) {
var previous = 0;
// 使用闭包返回一个函数并且用到闭包函数外面的变量previous
return function() {
var _this = this;
var args = arguments;
var now = new Date();
if(now - previous > delay) {
fn.apply(_this, args);
previous = now;
}
}
}
// 方式2
function throttle(fn, delay) {
var timer;
return function () {
var _this = this;
var args = arguments;
if (timer) {
return;
}
timer = setTimeout(function () {
fn.apply(_this, args);
timer = null; // 在delay后执行完fn之后清空timer,此时timer为假,throttle触发可以进入计时器
}, delay)
}
}
如何使用:
var myEfficientFn = throttle(function() {
// All the taxing stuff you do
}, 250);
window.addEventListener('resize', myEfficientFn);
//or call it manually:
myEfficientFn.apply();
文章评论