一,防抖(只执行最后一次)
防抖就是指连续触发事件但是在设定的一段时间内中只执行最后一次。
例如:设定1000毫秒执行,当触发事件了,会1000毫秒后执行。假设500毫秒的时候又触发了事件,那就会重新开始1000毫秒之后再执行。
具体应用:搜索框搜索提示,文本编辑器自动保存。
代码:每次调用函数时,清除以前的定时器,设置新的定时器。
let timer = null;
document.querySelector(".ipt").onkeyup = function () {
if (timer !== null) {
clearTimeout(timer);
}
timer = setTimeout(() => {
console.log("执行了");
}, 1000);
};
// 防抖函数封装
function debounce(fn, delay) {
let timer = null;
return function () {
if (timer !== null) clearTimeout(timer);
timer = setTimeout(() => {
fn();
}, delay);
};
}二,节流(只执行一次)
节流是指连续触发事件但是在设定的一段时间内只执行一次函数。
例如:设定1000毫秒执行,那么在1000毫秒内触发再多次,也只会在1000毫秒后执行一次。
具体应用: 高频事件,如快速点击、鼠标滚动、resize事件、scroll事件。 下拉加载。 视频播放记录时间等。
代码:
let timer = null;
document.querySelector(".ipt").onmouseover = function () {
if (timer !== null) return;
timer = setTimeout(() => {
console.log("执行了");
timer = null;
}, 1000);
};
// 节流函数封装
function throttle(fn, delay) {
let timer = null;
return function () {
if (timer !== null) return;
timer = setTimeout(() => {
fn();
timer = null;
}, delay);
};
}