JS闭包,防抖和节流

Js闭包

参考链接

function a() {
    var counter = 0;
    return function () {return counter += 1;}
}
var add = a();
add();
add();
add();

形式:函数里面嵌套函数
作用:访问函数的私有变量
特性:如上例,a函数返回一个匿名函数给add,并且add使用了a的变量counter,所以a函数不会被销毁回收,变量counter一直存在内存中,且只有add()可以访问。

Js防抖和节流

参考链接

防抖debounce: 当事件被触发时,设定一个周期延迟执行动作,若期间又被触发,则重新设定周期,直到周期结束,执行动作。
节流throttling: 节流的策略是,固定周期内,只执行一次动作,若有新事件触发,不执行。周期结束后,又有事件触发,开始新的周期。

如下对click添加防抖,时间间隔1s

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>防抖和节流</title>
	</head>
	<body>
		<input type="button" id='button' value="0" />
		<script>
			function debounce(fn, delay) {//防抖
				let timer = null //借助闭包
				return function() {
					if (timer) {
						clearTimeout(timer)
					}
					timer = setTimeout(fn, delay) // 简化写法
				}
			}
			let node=document.getElementById('button');
			function x(){
				node.value++;//这里如果使用this会指向window
			}
			node.onclick = debounce(x,1000);
		</script>
	</body>
</html>

如下对click添加节流,间隔时间为1s

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>防抖和节流</title>
	</head>
	<body>
		<input type="button" id='button' value="0" />
		<input type="button" id='button1' value="0" />
		<script>
			function debounce(fn, delay) {//防抖
				let timer = null;
				return function() {
					if(timer) {
						clearTimeout(timer);
					}
					timer = setTimeout(fn, delay);
				}
			}
			
			let node = document.getElementById('button');
			function x() {
				node.value++; //这里如果使用this会指向window
			}
			node.onclick = debounce(x, 1000);

			function throttling(fn,delay){//节流
				let flag = true;//工作中
				
				return function(){
					if(!flag) return false;
					flag = false;//挂机
					setTimeout(function(){
						fn();
						flag = true;//继续工作
					},delay);
				}
				
			}
			let node1 = document.getElementById('button1');
			function x1() {
				node1.value++; //这里如果使用this会指向window
			}
			node1.onclick = throttling(x1, 1000);
		</script>
	</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值