<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script src="./01、防抖实现.js"></script>
<input type="text" />
<button>取消</button>
<script>
const iptEle = document.querySelector("input");
const btn = document.querySelector("button");
let counter = 0;
const inputChange = function (event) {
console.log("1111------------", ++counter, this, event);
};
const handlerDebounce = Debounce(inputChange, 2000, true);
iptEle.oninput = handlerDebounce;
// 取消功能
btn.onclick = function () {
handlerDebounce.cancel();
};
</script>
</body>
</html>
/**
* 当事件触发时,相应的事件处理函数不会立即执行,而是会等待一定的时间再执行,只有在规定时间内没有事件触发,才会执行处理函数
*/
function Debounce(fn, delay, immediate = false) {
// 保存上一次定时器
let timer = null;
let isInvoke = false;
const _debounce = function (...args) {
// 取消上一次定时器
if (timer) clearTimeout(timer);
// 判断是否需要立即执行
if (immediate && !isInvoke) {
fn.apply(this, args);
isInvoke = true;
} else {
// 延时执行
timer = setTimeout(() => {
// 外部传入的函数调用
fn.apply(this, args);
isInvoke = false;
}, delay);
}
};
// 取消功能
_debounce.cancel = function () {
if (timer) clearTimeout(timer);
timer = null;
isInvoke = false;
};
return _debounce;
}