防抖和节流是项目开发中,经常使用到得是两个优化点;
防抖
节流的基本意思是,如果一个函数持续触发,在一定的时间后执行一次,如果这段时间内一直触发,都只会在这个时间后执行一次;适用于那些在连续触发时只关心最后一次触发的场景
项目实际中用到的场景:输入框搜索、监听页面滚动、键盘事件、窗口resize事件
// 防抖
function debounce(func, delay) {
let timeout;
return function() {
const context = this;
const args = arguments;
clearTimeout(timeout);
timeout = setTimeout(function() {
func.apply(context, args);
}, delay);
};
}
节流
防抖的基本意思是,如果一个函数持续触发,在这段时间内只执行一次;适用于那些需要在一定时间内保持执行的场景
项目实际中用到的场景:滚动事件、输入事件、动画效果、定时任务等
// 节流
function throttle(func, delay) {
let timer=null;
return function() {
const context = this;
const args = arguments;
if (!timer) {
timer = setTimeout(function() {
func.apply(context, args);
timer= null;
}, delay);
}
};
}
这里举例一个滚动到底部加载更多数据使用节流的例子
methods: {
// 获取数据
getList(){
},
throttle(func, delay) {
let timer=null;
return function() {
const args = arguments;
if (!timer) {
timer = setTimeout(function() {
func.apply(this, args);
timer= null;
}, delay);
}
};
},
handleScroll() {
const windowScrollTop =
window.pageYOffset || document.documentElement.scrollTop;
const windowHeight =
window.innerHeight || document.documentElement.clientHeight;
const contentHeight = document.getElementById("content").offsetHeight;
// 判断是否滚动到底部
if (windowScrollTop + windowHeight >= contentHeight) {
if (this.pageNum >= this.totalPages) {// 数据已经获取完毕
return;
}
this.isScroll = true;
this.pageNum += 1;
this.getList();
console.log("滚动到底部了");
}
},
},
mounted() {
window.addEventListener(
"scroll",
this.throttle(this.handleScroll, 500),
true
);
},
beforeDestroy() {
window.removeEventListener("scroll", this.handleScroll);
},