防抖和节流
防抖:在我们规定的间隔 n 秒后回调执行,若在 n 秒内被重复触发,则重新计时,回调只会执行一次
<body>
<div class="box">
<input type="text">
</div>
</body>
<script>
let input = document.querySelector('input')
input.addEventListener('input',antiShake(demo,1000))
//监听input事件
//封装防抖
function antiShake(fn,wait){
let time = null;
return ()=>{
if(time) clearTimeout(time)
time =setTimeout(fn,wait)
}
}
function demo(){
console.log('我最后执行了')
}
</script>
输入第一个字母:
input输入-》监听请求-》进入赛道等待1000ms -》
等待1000ms期间
继续不停输入-》监听请求-》不停清除赛道并进入赛道 -》直到输入结束-》监听结束-》最后一次清除赛道后进入赛道
-》执行demo()
节流:事件在我们规定的间隔 n 秒内多次执行,回调只会执行一次
<body>
<style>
.main{width: 300px;height: 300px;background-color: #f60;;}
</style>
<div class="box">
<div class="main"></div>
</div>
</body>
<script>
//节流 在移动下执行
let box = document.querySelector('.main');
box.addEventListener('touchmove',throttle(demo,1000))
function throttle(fn,wait){
let time = null
return function(){
if(!time){
time = setTimeout(()=>{
console.log(2) //第二步
fn()
time = null
},wait)
console.log(time) //第一步 time为1 关闭赛道
}
}
}
function demo(){
console.log('发起请求')
}
//1, 2, 发情请求
</script>
鼠标按下滑动第一下-》监听请求-》进入赛道-》time为1,关闭赛道 -》等待1000ms -》
等待期间
继续不停滑动-》1000ms后执行demo-》
循环往复上面的操作-》
直到滑动结束
-》监听结束-》最后一次进入赛道后-》执行demo()