防抖
防抖是在一定时间内只能有一次操作 => 将多次变为一次操作
<input placeholder="请输入电话">
let telInput = document.querySelector('input')
telInput.addEventListener('input',antiShake(demo,2000))
//防抖封装
function antiShake(fn,wait){
let timeOut = null
return () => {
if(timeOut) clearTimeout(timeOut)
timeOut = setTimeout(fn,wait)
}
}
function demo(){
console.log('发起请求')
}
节流
节流是一定时间内只调用一次函数 =>应用场景:1.提交表单 2.高频的监听事件
<div class="box"></div>
let box = document.querySelector('.box')
box.addEventListener('touchmove',throttle(demo,2000))
function throttle(event,wait){
let time = null
return args =>{
if(!time){
time = setTimeout(() =>{
event()
time = null
},wait)
}
}
}
function demo (){
console.log('发送请求')
}