防抖
你尽管触发事件,但我一定在事件触发n秒后才执行,如果在一个事件触发的n秒内又触发了这个事件,就以新的事件的事件为准, n秒后才执行。总之触发完事件n秒内不再触发事件,才执行新的事件
function debounce(fun, delay, immediate) {
let timer;
function debounced() {
const args = [...arguments];
clearTimeout(timer);
if(immediate) {
if(!timer) {
fun.apply(this,args);
}
timer = setTimeout(() => {
timer = null;
}, delay);
} else {
timer = setTimeout(() => {
fun.apply(this,args);
}, delay);
}
}
debounced.cancel = function() {
clearTimeout(timer);
timer = null;
}
return debounced;
}
function debounce(fn, delay, immediate) {
let timer = null;
function debounced() => {
clearTimeout(timer);
if(immediate) {
if(!timer) {
fn.apply(this, arguments);
} else {
timer = setTimeout(() => {
timer = null;
}, delay)
}
} else {
timer = setTimeout(() => {
fn.apply(this, arguments);
}, delay)
}
}
debounced.cancal = function() {
if(timer) {
clearTimeout(timer);
timer = null;
}
}
}
节流
一段时间只执行一次,根据首次是否执行以及结束后是否执行,效果与实现方式都有所不同。用leading代表首次是否执行,trailing代表结束后是否再执行一次
function throttle(fn, delay, leading, trailing) {
let timer = null;
return (() => {
if(leading) {
if(!timer) {
fn.apply(this, arguments);
timer = setTimeout(() => {
timer = null;
}, delay);
}
}
if(trailing) {
if(!timer) {
timer = setTimeout(() => {
fn.apply(this, arguments);
timer = null;
}, delay);
}
}
}