1. 防抖
触发高频率事件在n秒后函数会触发一次,n秒内触发高频率事件,重新计算时间
举个例子:
就像进电梯,电梯开启后,有一群人要进电梯,假如电梯3s内不进人就会关闭,现在不断有人进入。进电梯就是高频率事件,前一个人进去后,后面的人重新开始计时,,事件不断触发。当最后一个人进入后,3s后电梯开始关闭。
var inp = document.getElementById('input');
function debounce(handler,wait) {
var timer = null;
return function () { //返回的匿名函数就是oninput的逻辑处理
clearTimeout(timer);
timer = setTimeout(() => {
handler.apply(this, arguments); //this指向input框,arguments就是input事件e,当做参数传入handler
},wait)
}
}
function sayHi(e) {
console.log(e, this.value);
}
inp.addEventListener('input',debounce(sayHi, 2000))
2. 节流
以时间为单位稀释执行次数,上次执行n秒后可再次执行
var btn = document.getElementById('btn');
function throttle(handler,wait) {
let lastTime = 0;
return function () {
const nowTime = +new Date(); //时间戳
if (nowTime - lastTime > wait) {
handler.apply(this, arguments);
lastTime = nowTime;
}
}
}
function sayHi(e) {
console.log(this,e);
}
btn.onclick = throttle(sayHi, 2000);