防抖、节流

undescore lodash  debounce throttle    
一、防抖

防抖:在一定时间内再次触发该函数,则会重新计算时间,超过预定时间,则会执行最后一次函数(事件被频繁触发,在规定的时间内一直触发函数,会重新计算时间,直到达到时间,函数才会执行最后一次)

目的:优化高频率事件触发得手段

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
	<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>
</html>

二、节流

节流:每隔一段时间函数只会执行一次,限制事件执行得频率(事件被频繁的触发 每隔一段时间函数最多执行一次 )

目的:优化高频率发生事件  鼠标移动 滚动条 搜索框
    lodash undescore 
    npm install lodash undescore -S
    var _ = require('lodash');
    input.oninput = _.debounce(function(){
        xxxxx
    },1000)
    input.oninput = _.throttle(function(){
        xxxxx
    },1000)

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
	<style>
		body{
			height: 3000px;
		}
	</style>
	<script>
		window.onscroll = throttle(function(){
			alert('我被调用了')
		},2000)
		function throttle(fun,wait){
			// 定义一个变量控制定时器执行的频率
			// let t = true;
			let id;
			return function(){
					if(!id){
						id = setTimeout(function(){
							fun();
							// t=true;
						// 为了持续等待wait事件执行定时器一次
							id = null;
						},wait);
					}
				// 限制事件执行频率
				// t = false;
			}
		}
	</script>
</head>
<body>	
</body>
</html>

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值