什么是防抖和节流?有什么区别?如何实现?

什么是防抖和节流?有什么区别?如何实现?

防抖:触发高频事件时,事件在n秒内只执行一次,如果在n秒内再次触发,则重新计算时间

实现:
function debounce(func,wait){
	let timer = null //定时器
	return function(){
	 //保存当前调用的dom对象
	 let _this = this
	 //保存当前事件对象
	 clearTimeout(timer)  //如果在指定时间又触发了,就清楚定时器,不让他执行下面的func
	 timer = setTimeout(function(){
	 		//用apply改变func的this指向,使是当前调用的dom对象,顺便把事件对象传过去
			func.apply(_this,arg)
},wait) 
}
}
function say(){
console.log(this,arg)
console.log('防抖')
}
let inp = document.getElementById('inp')
inp.addEventListener('input',debounce(say,1000))

节流:高频事件触发,但在n秒内只会执行一次,所以节流会稀释函数的执行频率

实现

function throttle(func,wait){
    let timer = null
    return function(){
	let _this = this
	let args = arguments
	if(!timer){
	timer = setTimeout(function(){
		timer = null
		func.apply(_this,args)
},wait)
}
}
}

function say(e){
console.log(e.target.innerWidth,e.target.innerHeight)
}
window.addEventListener('resize',throttle(say,200))

场景使用

防抖:

search搜索联想,用户在不断输入值时,用防抖来节约请求资源
登录、发短信等按钮避免用户点击太快,以致于发送了多次请求,需要防抖

节流:

window触发resize的时候,不断的调整浏览器窗口大小会不断的触发这个事件,用防抖来让其只触发一次

总结

防抖:防止抖动,单位时间内事件触发会被重置,避免事件被误伤触发多次。
节流:节流:控制流量,单位时间内事件只能触发一次,如果服务器端的限流即 Rate Limit

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值