防抖(debounce),是指在触发事件后n秒内函数只执行一次,如果在n秒内又触发了事件,则会重新计算函数执行时间。
function debounce(func, wait) {
let timer;
return function () {
const context = this;
const args = arguments;
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
func.apply(context, args)
}, wait);
}
}
// 只有在触发事件后的n秒内不再次触发事件,才会执行函数
const deFunc = debounce(func, 1000);
节流(throttle),是指连续触发事件,但在n秒内只执行一次函数,稀释函数的执行频率。
// 定时器
function throttle (func, wait) {
let timer;
return function () {
const context = this;
const args = arguments;
if (!timer) {
timer = setTimeout(() => {
timer = null;
func.apply(context, args);
}, wait);
}
}
}
// 时间戳
function throttle (func, wait) {
let previous = 0;
return function () {
const context = this;
const args = arguments;
const current = new Date();
if (current - previous > wait) {
func.apply(context, args);
previous = current;
}
}
}
// 事件连续触发,但函数每隔n秒执行一次
const thFunc = throttle(func, 1000);