- 函数节流是指一定时间内js方法只运行一次
- 函数防抖是指频繁触发的情况下,只有足够的空闲时间,才运行一次
function debounce(fn, delay, immediate) {
let timer;
return function () {
let _this = this,
args = arguments;
if (timer) clearTimeout(timer);
if (immediate) {
let callNow = !timer;
timer = setTimeout(() => {
timer= null;
fn.apply(_this, args);
}, delay);
if (callNow) fn.apply(_this, args);
} else {
timer = setTimeout(() => {
fn.apply(_this, args);
}, delay);
}
}
}
function throttle (fn, delay, immediate) {
let timer, startTime = 0;
return function () {
let _this = this,
args = arguments;
if (immediate) {
let now = Date.now();
if (now - startTime > delay) {
fn.apply(_this, args);
startTime = now;
}
return;
}
if (!timer) {
timer = setTimeout(function () {
timer = null;
fn.apply(_this, args);
}, delay);
}
}
}