防抖:设定一个时间,如果用户频繁触发事件,只取最后一次事件的操作
监听input输入框的value
<input type="text"/>
let inp = document.querySelector("input");
let t = null
inp.oninput = function () {
if (t !== null) {
clearTimeout(t)
}
t = setTimeout(() => {
console.log(this.value);
},1000);
};
用闭包封装防抖函数 / 防抖
// 用闭包封装一个防抖的函数
inp.oninput = debounce(function () {
console.log(this.value);
}, 500);
function debounce(fn, delay) {
let t = null;
return function () {
if (t !== null) {
clearTimeout(t);
}
t = setTimeout(() => {
// 直接调用fn() this指向的是全局,这里需要改变下this指向
fn.call(this);
}, delay);
};
}
节流:当持续触发事件时,保证一定时间里,只调用一次事件处理函数,比如监听滚动条的变化发起请求,肯定不能滚动条动一下就发起一次请求,所以要用节流限制发起请求的次数
let flag = true;
window.onscroll = function () {
if (flag) {
setTimeout(() => {
console.log("hello world");
flag = true;
}, 500);
}
flag = false;
};
用闭包封装成函数 / 节流
window.onscroll = throttle(function () {
console.log("hello world");
}, 500);
function throttle(fn, delay) {
let flag = true;
return function () {
if (flag) {
setTimeout(() => {
fn.call(this);
flag = true;
}, delay);
}
flag = false;
};
}