防抖
防抖意思是将一段时间内连续的多次触发转化为一次有效触发。
function debounce(func, ms = 1000) {
let timer;
return function (...args) {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
func.apply(this, args)
}, ms)
}
}
节流
节流顾名思义则是将减少一段时间内触发的频率。
function throttle(func, ms = 1000) {
let canRun = true;
return function (...args) {
if (!canRun) return;
canRun = false;
setTimeout(() => {
func.apply(this, args);
canRun = true;
}, ms)
}
}