<!DOCTYPE html>
<html lang="en">
<body>
<button id="debounce">点击触发</button>
<script>
window.onload = function () {
var myDebounce = document.getElementById("debounce");
//绑定事件
myDebounce.addEventListener("click", debounce(sayDebounce, 'a', 'b'));
}
//防抖函数
function debounce(fn, ...args) {
let timeout = null;
return function () {
clearTimeout(timeout); //当未满一秒再次调用函数时,重新调用定时器
timeout = setTimeout(() => { //一秒后触发函数
fn.apply(this, args); //将防抖函数参数传入,并改变this指向
}, 1000);
};
}
function sayDebounce(a, b) {
console.log("防抖成功!");
console.log(a)
console.log(b)
}
</script>
</body>
</html>