防抖是控制次数,节流是控制频率
函数防抖和节流 - 简书
/**
* @desc 函数节流
* @param func 函数
* @param wait 延迟执行毫秒数
* @param type 1 表时间戳版,2 表定时器版
*/
function throttle(func, wait, type = 1) {
let previous = 0;
let timeout;
return function () {
let context = this;
let args = arguments;
if (type === 1) {
let now = Date.now();
if (now - previous > wait) {
func.apply(context, args);
previous = now;
}
} else if (type === 2) {
if (!timeout) {
timeout = setTimeout(() => {
timeout = null;
func.apply(context, args)
}, wait)
}
}
}
}
/**
* 函数防抖,就是指触发事件后,在 n 秒后只能执行一次,如果在 n 秒内又触发了事件,则会重新计算函数的执行时间。
* @param {Function} 执行函数
* @param {number} 时间间隔,默认为300
* @returns {Function}
*/
function debounce(fn, interval) {
let timer;
let delay = interval || 1000; // 间隔的时间,如果interval不传,则默认1秒
return function () {
let that = this;
let args = arguments; // 保存此处的arguments,因为setTimeout是全局的,arguments不是防抖函数需要的。
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(function () {
fn.apply(that, args); // 用apply指向调用debounce的对象,相当于this.fn(args);
}, delay);
};
}