防抖和节流的应用在开发过程中遇到的频率相当高,如果处理不当或者放任不管就容易引起浏览器卡死。
节流 throttle
高频事件触发,但在n秒内只会执行一次,所以节流会稀释函数的执行频率
function throttle(fn,wait) {
// 节流
let last = 0;
return function (...params) {
const nowData = new Date().getTime();
if(!last||nowData - last > wait){
fn.apply(this,params);
last = nowData;
}
}
}
function throttleTest(a){
console.log(a)
}
const throttleFn = throttle(throttleTest,2000);
throttleFn('throttle1');
throttleFn('throttle2');
setTimeout(()=>{
throttleFn('throttle3');
},5000)
// throttle1
// throttle3
防抖 debounce
触发高频事件后n秒内函数只会执行一次,如果n秒内高频事件再次被触发,则重新计算时间。
function debounce(fn,await) {
let timer = null;
return function (...arg){
if(timer){
clearTimeout(timer);
timer = null;
}
timer = setTimeout(()=>{
fn.apply(this,arg);
timer = null;
},await)
}
}
function debounceTest(a){
console.log(a)
}
const debounceFn = debounce(debounceTest,2000);
debounceFn(1);
debounceFn(2);
// 2