节流阀
更像是一个思想
一间房子只能睡一个人
1:进入房间,默认门是开着的,(flag = true)可以直接进来睡觉
2:为了确保安全,需要将门关上(flag = false)
3:睡觉结束(一个事件完成) 需要离开 让下一个进来睡觉,将门打开(flag = true)
如此反复,确保在睡觉这个事件上,一次只能睡一个人
var btn = document.querySelector('button');
var flag = true;
var timer;
btn.onclick = function(){
// 定时器可以写在if里面也可以写在外面 如果写在外面必须清除定时器 否则会创建多个定时器 导致flag 很快为true
// 如果写在里面 想要执行定时器,必须通过if语句,确保定时器安全
clearTimeout(timer)
if(flag == true){
flag = false;
console.log(1)
}
timer = setTimeout(function(){
flag = true
},2000)
}
函数节流 :高频事件触发,但在n秒内只会执行一次,所以节流 会稀释函数的执行频率
函数防抖
触发高频事件后n秒内函数只会执行最后一次,因为如果n秒内高频事件再次被触发则重新计算时间
<div style="height: 5000px; background-color: yellow;"></div>
function debounce(fn,delay){
var timer = null;
return function(e){
console.log(1)
// 清除定时器
clearTimeout(timer)
// 创建了一个新的setTimeout 这样可以保证 n秒内 如果事件再次触发 就不会执行fn函数
timer = setTimeout(()=>{
fn()
},delay)
}
}
// 处理函数
function handle(){
console.log("防抖",Math.random());
}
// 滚动事件
window.addEventListener('scroll',debounce(handle,500))
每次触发滚动事件,需等待0.5秒才能执行。在这0.5秒内再次触发,会清除之前定时器,重新计时,0.5秒后执行。如果不停触发,就永远不会执行。