js--防抖与节流

本文深入探讨了JavaScript中的两种性能优化技术——防抖和节流。防抖技术用于限制函数的执行频率,确保在用户频繁触发事件时只执行最后一次操作,而节流则控制高频事件的触发,避免在滚动等操作中过度消耗资源。通过实例代码展示了如何实现防抖和节流,并通过闭包进行封装,以提高代码的可维护性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天复习一下js中的防抖与节流。
一、防抖:用户触发过于频繁,只要最后一次事件操作
1、代码展示

<style>
	body{
		height:2000px;
	}
</style>
	<input type="text">
<script>
	let inp = document.querySelector("input");
	inp.oninput = function(){
	console.log(this.value)
}
</script>

2、问题场景:当我们往输入框输入数据的时候,每输入一次的时候控制台就会打印一次,但是我们想的是当输入最后一个字母的时候才会打印出来,这就是我们要解决的防抖
在这里插入图片描述
3、最简单的防抖,但是防抖代码和业务代码放在了一起,并且还有全局变量,因此极不推荐这样写

<style>
	body{
		height:2000px;
	}
</style>
	<input type="text">
<script>
		let inp = document.queySelector("input");  //先获取到该标签
		let t = null;
		inp.oninput = function(){  //通过oninput来向标签中添加数据
		if( t !=null){  //若不是最后一次事件的操作有数据的输入则清除
		clearTimeout(t)
	}
	//最后一次执行事件操作
	t = setTimeout( () => {
		console.log( this.value)
},500)
}
</script>

4、为了解决上面的问题因此可以通过使用闭包来实现对防抖的封装

<style>
	body{
		height:2000px;
	}
</style>
	<input type="text">
<script>
	let inp = document.querySelector("input");
	inp.document = debounce( function(){
		console.log(this.value)
	},500)

//利用闭包封装
function debounce(fn,delay){
	let t = null;
	return function(){
		if( t != null){
			clearTimeout(t);
		}
		t = setTimeout( () => {
			fn.call(this)
		},delay)
	}
}
</script>

二、节流:控制高频事件的触发,比如我们下拉滑动块的时候事件的频繁触发
1、最基本的节流,同样问题很多,不提倡使用

<style>
	body{
		height:2000px;
	}
</style>
	<input type="text">
let flag = true;
window.onscroll = function(){
	console.log("hello world");
	if(flag){
		setTimeout( ()=>{
			console.log("hello world");
			flag = true;
		},1000 )
	}
	flag = false;
}

2、通过闭包来实现对节流的封装

<style>
	body{
		height:2000px;
	}
</style>
	<input type="text">
<script>
window.onscroll = throttle(function(){
console.log("hello world")
},500)
	

//利用闭包封装
function throttle(fn,delay){
	let flag = true;
	return function(){
		if(flag){
				setTimeout( () =>{
					fn.call(this);
					flag = true;
				},delay)
			}
		flag = false;
		
	}

}
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值