// 防抖函数 延时执行
function debounce1(fn, wait) {
let timer = null;
return function () {
let _this = this;
let args = arguments;
if (timer) {
clearTimeout(timer);
timer = null;
}
timer = setTimeout(() => {
fn.apply(_this, args)
}, wait)
}
}
// 防抖函数 立即执行
function debounce2(fn, wait) {
let timer;
return function () {
let _this = this;
let args = arguments;
if (timer) {
clearTimeout(timer)
}
let applyNow = !timer;
timer = setTimeout(() => {
timer = null;
}, wait)
if (applyNow) {
fn.apply(_this, args)
}
}
}
// 节流函数 时间戳版本
function throttle1(fn, delay) {
let curTime = Date.now();
return function () {
let _this = this;
let args = arguments;
let now = Date.now();
if (now - curTime >= delay) {
curTime = Date.now();
fn.apply(_this, args)
}
}
}
//节流函数 定时器版本
function throttle2(fn, wait) {
let timer = null;
return function () {
let _this = this;
let args = arguments;
if (!timer) {
timer = setTimeout(() => {
timer = null;
fn.apply(_this, args)
}, wait)
}
}
}
console