防抖和节流是在js性能优化方面非常重要的一环,它们主要针对的是一些短时间内会被频繁触发的事件;
防抖
当用户连续触发后,函数在指定时间内执行一次
function debounce(callBack, time) {
let timer = null;
return function () {
const _this = this;
const arg = arguments;
if(timer) {
clearInterval(timer)
}
timer = setTimeout(function() {
timer = null;
callBack.apply(_this, arg);
}, time);
}
}
function handle() {
console.log(Math.random())
}
addEventListener('scroll', debounce(handle, 1000)) // 对于短时间内连续触发的事件,当结束操作后,100毫秒后函数执行一次。
节流
在用户连续触发事件的过程中,每隔指定时间内执行一次
const thorttle = function (callBack, time) {
let preTime = new Date();
return function () {
const _this = this;
const param = arguments;
const currTime = new Date();
if(currTime - preTime >= time) {
callBack.apply(_this, param);
preTime = new Date()
}
}
}
function Handle() {
console.log(Math.random())
}
addEventListener('scroll', thorttle(Handle, 1000)) // 对于短时间内连续触发的事件,当结束操作后,100毫秒后函数执行一次。