防抖的实现

<!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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值