一、防抖
1、定义:触发高频事件后,n 秒内函数只会执行一次。如果 n 秒内高频事件再次被触发,则重新计算时间。
2、常用事件:
(1)搜索框搜索输入。只需用户最后一次输入完,再发送请求
(2)手机号、邮箱验证输入检测 onchange oninput事件
(3)窗口大小Resize。只需窗口调整完成后,计算窗口大小。防止重复渲染。
3、代码实现:
(1)函数
const antiShake = (fn, wait, immediate) => {
let timer = null;
return function (...args) {
if (timer) clearTimeout(timer);
if (immediate && !timer) {
fn.call(this, args);
}
timer = setTimeout(() => {
fn.call(this, args);
}, wait);
};
};
const betterFn = antiShake (() => console.log(" 防抖执行了 "), 1000, true);
document.addEventListener("scroll", betterFn);
(2)vue 实现
<script>
export default {
data() {
return {
timer: null
};
},
methods: {
antiShake () {
clearTimeout(this.timer);
this.timer = setTimeout(() => {
console.log('防抖执行');
}, 200);
}
}
};
</script>
二、节流
1、定义:在单位时间内, 只会触发一次事件。如果事件触发后,再次重复触发了同一事件,则忽略后面触发的事件,直到第一次事件的计时结束。
2、常用事件:
(1)懒加载、滚动加载、加载更多或监听滚动条位置;
(2)百度搜索框,搜索联想功能;
(3)防止高频点击提交,防止表单重复提交;
3、代码实现:
(1)函数
function throttle(fn,wait){
let pre = 0;
return function(...args){
let now = Date.now();
if( now - pre >= wait){
fn.apply(this,args);
pre = now;
}
}
}
function handle(){
console.log(Math.random());
}
window.addEventListener("mousemove", throttle(handle,1000));
(2)vue 实现
<script>
export default {
data() {
return {
isFinshed: true
};
},
methods: {
throttle() {
if (this.isFinshed === true) {
this.isFinshed = false;
this.timer = setTimeout(() => {
console.log('节流执行');
this.isFinshed = true;
}, 200);
}
}
}
};