防抖(debounce)
// npm 节流去抖工具包 throttle-debounce
防抖(debounce):指的是某个函数在某个时间段内,无论触发多少次,都只执行最后一次。
代码如下:
function debounce(fn, wait=100) {
// 设定定时器
let timer = null;
return function(...args) {
if(timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fn.apply(this, args)
}, wait);
}
}
// 定义一个实例接收
const bus = debounce(() => {
const node = document.createElement("span");
const textNode = document.createTextNode("?");
node.appendChild(textNode);
document.getElementById("debounceImg").appendChild(node);
console.log("有人上车了, 请再等一等!");
}, 1000);
document.getElementById("debounce").addEventListener("scroll", bus);