防抖(debounce)
一句话概况防抖就是将多次操作合并为一次操作。用代码的话来说就是:开启一个定时器,在规定时间内如果触发多次事件则清空定时器重新计时,否则才执行
function debounce(fn, delay) {
let timer = null;
return function() {
const _this = this;
const args = arguments;
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fn.apply(_this, args);
}, delay);
}
}
节流(throttle)
节流类似于番剧,雷打不动的固定一周更新一集(大概)。
定时器版:
function throttle(fn, delay) {
let timer = null;
return function() {
const _this = this;
const args = arguments;
if (timer) { return; }
timer = setTimeout(() => {
fn.apply(_this, args);
timer = null;
}, delay);
}
}
时间戳版:
function throttle(fn, delay) {
let now = 0;
return function() {
let prev = Date.now();
const _this = this;
const args = arguments;
if (prev - now >= delay) {
fn.apply(_this, args);
now = prev;
}
}
}