防抖
防抖 (debounce): 将多次高频操作优化为只在最后一次执行,通常使用的场景是:用户输入,只需再输入完成后做一次输入校验即可。
function debounce(fn, wait, immediate) {
let timer = null;
return function() {
let args = arguments;
let context = this;
if (immediate) {
fn.apply(context, args);
}
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(context, args);
}, wait)
}
}
节流
节流(throttle): 每隔一段时间后执行一次,也就是降低频率,将高频操作优化成低频操作,通常使用场景: 滚动条事件 或者 resize 事件,通常每隔 100~500 ms 执行一次即可。
简易实现:
function throttle(fn, wait, immediate) {
let timer = null;
let callNow = immediate;
return function() {
const args = arguments;
const context = this;
if (callNow) {
fn.apply(context, args);
callNow = false;
}
if (!timer) {
timer = setTimeout(() => {
fn.apply(context, args);
timer = null;
}, wait);
}
}
}
复杂实现:
function throttle(fn, wait) {
let context;
let timer;
let previous = 0;
return function() {
context = this;
const args = arguments;
const now = +new Date();
const t = wait - (now - previous);
if (t <= 0) {
if (timer) {
clearTimeout(timer);
timer = null;
}
fn.apply(context, args);
previous = now;
} else if (!timer) {
timer = setTimeout(() => {
fn.apply(context, args);
timer = null;
previous = +new Date();
}, t);
}
}
}