一
防抖:单位时间内,频繁触发事件,只执行最后一次
场景:搜索框搜索输入(利用定时器,每次触发先清掉以前的定时器,从新开始)
节流:单位时间内,频繁触发事件,只执行一次
场景:高频事件 快速点击,鼠标滑动、resize事件、scroll事件(利用定时器,等定时器执行完毕,才开启定时器,不用打断)
一般用lodash库,利用里面的debounce(防抖)和throttle(节流)来做
二
【前端面试题:防抖与节流(二)】 https://www.bilibili.com/video/BV1ig411u7LG/?share_source=copy_web&vd_source=c1fe9c75396fdc6f65b56d15f5eb00b3
防抖
防抖:用户触发事件过于频繁,只需要最后一次事件的操作
案例一:输入框触发过于频繁
 
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<input type="text">
		<script>
		let inp = document.querySelector("input");
		inp.oninput = function(){
			console.log(this.value);
		}
		</script>
	</body>
</html> 
案例二:用定时器解决触发频繁问题
 
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<input type="text">
		<script>
		// 防抖方法一  好烦啊,我也不知道是哪些部分不懂,明明拆开我全晓得,烦躁
		 let inp = document.querySelector("input");
		 // t代表的是用户触发的次数
		 let t = null;
		 inp.oninput = function(){
		 	if(t !== null){
				clearTimeout(t);
			}
			t = setTimeout(()=>{
				console.log(this.value);
			},500)
		}
		
		</script>
	</body>
</html> 
案例三:用debounce解决触发频繁问题
案例二的代码据说是一团垃圾,因为业务逻辑和什么混在一起了,所以下面用闭包封的更好些
 
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<input type="text">
		<script>
			// 防抖方法二 debounce
		let inp = document.querySelector("input");
		let t = null;
		inp.oninput = debounce(function(){
			console.log(this.value);
		},500)
		
		function debounce(fn,delay){
			return function(){
				if(t !== null){
					clearTimeout(t);
				}
				t = setTimeout(()=>{
					fn.call(this);
				},delay)
			}
		}
		
		</script>
	</body>
</html> 
节流
节流就是控制执行次数
案例一:执行次数过多

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style>
			body{
				height:800px;
			}
		</style>
	</head>
	<body>
		<script>
			window.onscroll = function(){
			 	console.log("123");
			}
		</script>
	</body>
</html> 
案例二:定时器节流

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style>
			body{
				height:800px;
			}
		</style>
	</head>
	<body>
		<script>
		// 节流方法一 定时器
		let flag = true;
		window.onscroll = function(){
			if(flag){
				setTimeout(()=>{
					console.log("111");
					flag = true;
				},500)
			}
			flag = false;
		}
		</script>
	</body>
</html> 
案例三:throttle节流

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style>
			body{
				height:800px;
			}
		</style>
	</head>
	<body>
		<script>
		// 节流方法二:throttle
		let flag = true;
		window.onscroll = throttle(function(){
			console.log("111");
		},500)
		function throttle(fn,delay){
			let flag = true;
			return function(){
				if(flag){
					setTimeout(()=>{
						fn.call(this)
						flag = true
					},delay)
				}
				flag = false;
			}
		}
		</script>
	</body>
</html> 
 
三
【手写函数防抖和节流】 https://www.bilibili.com/video/BV1pQ4y1M71e/?p=3&share_source=copy_web&vd_source=c1fe9c75396fdc6f65b56d15f5eb00b3



















