防抖和节流

本文介绍了JavaScript中的防抖(debounce)和节流(throttle)技术,用于优化高频事件处理,如输入框搜索和页面滚动。防抖确保在规定时间内只执行最后一次函数,而节流则保证事件在设定间隔内最多执行一次。示例代码展示了如何使用lodash库以及自定义实现防抖和节流函数。
摘要由CSDN通过智能技术生成


    防抖:事件被频繁触发,在规定的时间内一直触发函数,会重新计算时间,直到达到时间,函数才会执行最后一次
     执行函数的最后一次代码 
    节流:事件被频繁的触发 每隔一段时间函数最多执行一次 
    目的:优化高频率发生事件  鼠标移动 滚动条 搜索框
  

 lodash undescore 
    npm install lodash undescore -S
    var _ = require('lodash');
    input.oninput = _.debounce(function(){
        xxxxx
    },1000)
    input.oninput = _.throttle(function(){
        xxxxx
    },1000)

防抖:

<script>
		window.onload = function(){

			var input = document.querySelector('input');
			input.oninput = debounce(function(){
				console.log(this.value)
			},1000);
			function debounce(fun,wait){
				let timer = null;
				return function(){
				// console.log(this.value,'获取输入框的值')
				if(timer!=null){
					clearTimeout(timer)
				}
				var that = this;
				timer = setTimeout(function(){
						fun.call(that)
					},wait)
				}
			}
		}
	</script>
</head>
<body>
	<input type="text">
</body>

节流:

	<style>
		body{
			height: 3000px;
		}
	</style>
	<script>
		window.onscroll = throttle(function(){
			alert('我被调用了')
		},2000)
		function throttle(fun,wait){
			// 定义一个变量控制定时器执行的频率
			let id;
			return function(){
					if(!id){
						id = setTimeout(function(){
							fun();
						// 为了持续等待wait事件执行定时器一次
							id = null;
						},wait);
					}
				// 限制事件执行频率
				// t = false;
			}
		}
	</script>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值