js的防抖节流方法,之前写过,现在在做后台数据滚动加载,触底方法需要用到,就再写一遍,记录一下,后续再用也方便找了。
节流——保证一定时间内只调用一次
应用场景:提交表单、高频的监听事件
移动端,触摸移动就会发起请求
将一定时间内的多个事件合并成一个
let box = document.querySelector('.box')
/* box.addEventListener('touchmove',e=>{
console.log('请求')
}) */
//节流函数
function throttle(event, time){
let timer = null
return _=>{
if(!timer){
timer = setTimeout(_=>{
event()
timer = null
}, time)
}
}
}
box.addEventListener('touchmove',throttle(_=>{console.log('请求')}, 1000))
防抖 —— 在固定的时间内,事件仅允许发生一次
例如:在下面输入时,会立刻发送请求,防抖就是限制在输入结束后2秒再发送请求
//抖动案例
let telInput = document.querySelector('input')
/* telInput.addEventListener('input', e=>{
console.log('发起请求')
}) */
//防抖函数
function antiShake(fn, wait){
let timeOut = null;
console.log('防抖函数')
return _ => {
console.log('timer',timeOut)
if(timeOut) clearTimeout(timeOut)
timeOut = setTimeout(fn, wait)
}
}
//上面案例使用防抖函数
telInput.addEventListener('input', antiShake( _=>{console.log('发起请求')} , 2000))
以上两个方法比较常用,借用了闭包的原理,记录一下。