//防抖 =>固定的时间内,事件仅允许发生一次(多变一)
let tel = document.querySelector("input")
tel.addEventListener("input",antiShake(demo,2000))
//防抖封装
function antiShake(fn,wait){
let timeOut = null;
return args =>{
if(timeOut) clearTimeout(timeOut)
timeOut=setTimeout(fn,wait);
}
}
function demo(){
console.log("正在发送请求");
}
//节流 => 一定时间内只调用一次函数
//应用场景 => 1.提交表单 2.高频监听事件
let box = document.querySelector("div")
box.addEventListener("mouseenter",throttle(demo,2000))
function throttle(event,time){
let timer = null
return function(){
if(!timer){
timer = setTimeout(()=>{
event();
timer = null ;
},time)
}
}
}
防抖就是在输入号码的时候一次性输入多位数字也就会在后台响应多次,非常消耗网速(bushi)
于是设置定时器,当按一次数字后两秒钟之后才在控制台成功发送请求。也就是在固定时间内事件仅允许发生一次。
节流就好像是将一束大水龙头慢慢变成小水流一样,在一定时间内只调用一次函数