前端面试题:节流和防抖

本文介绍了JavaScript中的节流和防抖两种技术,它们通过控制事件执行频率来节省资源。节流确保在一定时间间隔后只执行一次,而防抖则是在一段时间内连续触发时只执行最后一次。作者提供了详细的代码示例和应用场景分析。
摘要由CSDN通过智能技术生成

节流和防抖都是通过降低事件执行的频率而达到节省资源的效果

节流

一段时间只执行一次,多少秒之后获取验证码、resize 事件和scroll 事件等

类似王者荣耀中的传送,一段时间内只能传送一次,具体实现如下:

function throttle(fn, delay) {
				let lastTime = 0;
				return function () {
					let currentTime = Date.now();
					if (currentTime - lastTime > delay) {
						lastTime = currentTime;
						fn.apply(this, arguments);
					}
				};
}

防抖

一段时间内连续触发事件,只执行最后一次,如搜索,手机号、邮箱地址的校验

类似王者荣耀中的回城操作,如果被打断则重新计时,不打断则执行最后一次操作。

代码实现如下:

function debounce(fn, delay) {
				let timer = null;
				return function () {
					if (timer) {
						clearTimeout(timer);
					}

					timer = setTimeout(() => {
						fn.apply(this, arguments);
					}, delay);
				};
}

具体应用实现如下:

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>Document</title>
		<style>
			.box {
				width: 100px;
				height: 100px;
				background-color: blue;
			}
		</style>
	</head>
	<body>
		<div class="box"></div>
		<input class="input" />

		<script>
			const domBox = document.querySelector(".box");
			const domIpt = document.querySelector(".input");
			console.log("🚀 ~ file: 节流.html:20 ~ domBox:", domBox);
			function throttle(fn, delay) {
				let timer = null;
				return function () {
					if (timer) {
						clearTimeout(timer);
						timer = null;
					}

					timer = setTimeout(() => {
						// fn.apply(this, arguments);
						fn.call(this, ...arguments);
					}, delay);
				};
			}
			// 节流一段时间只执行一次,多少秒之后获取验证码、resize 事件和scroll 事件等
			function throttle(fn, delay) {
				let lastTime = 0;
				return function () {
					let currentTime = Date.now();
					if (currentTime - lastTime > delay) {
						lastTime = currentTime;
						fn.apply(this, arguments);
					}
				};
			}
			// 防抖:一段时间内连续触发事件,只执行最后一次,如搜索,手机号、邮箱地址的校验
			function debounce(fn, delay) {
				let timer = null;
				return function () {
					if (timer) {
						clearTimeout(timer);
					}

					timer = setTimeout(() => {
						fn.apply(this, arguments);
					}, delay);
				};
			}
			domBox.addEventListener(
				"click",
				throttle(e => {
					console.log("click dom box", e);
				}, 1000)
			);

			domIpt.addEventListener(
				"input",
				debounce(function (event) {
					console.log("debounce event =>", event);
				}, 500)
			);
		</script>
	</body>
</html>

  • 18
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

华子Code1024

您的认可与打赏是我创作的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值