防抖与节流
防抖与节流⭐⭐
防抖---点击多次取最后一次
//样式style
<style>
*{
margin: 0px;
padding: 0px;
list-style: none;
}
/* 防抖 */
.fd {
margin: 40px auto;
cursor: pointer;
width: 200px;
height: 200px;
background-color: lightblue;
overflow: hidden;
display: flex;
justify-content: center;
flex-direction: column;
}
.fd>p {
margin: 0 auto;
font-size: 20px;
font-weight: bold;
color: bisque;
}
.fd>span{
font-size: 50px;
line-height: 50px;
text-align: center;
}
</style>
//body
<div class="fd">
<p>防抖</p>
<span>1</span>
</div>
//js
<script>
let i = 1;
let timer = null;
let arr = ['blur', 'red', 'green', 'pink', '#3434e3']
let fd = document.querySelector(".fd");
fd.onclick = function () {
fd.children[1].innerHTML = i++;//children[1]获取的是span元素
clearTimeout(timer);
timer = setTimeout(() => {
fd.style.backgroundColor = arr[parseInt(Math.random() * 5 + 1)]
}, 1000)
}
</script>
防抖效果图


(注:这里颜色只变换了一次,但点击了六次,点击六次期间颜色没有变化)
节流---一段时间触发一次
<style>
.jl {
margin: 0px auto;
cursor: pointer;
width: 200px;
height: 200px;
background-color: rgb(176, 113, 212);
overflow: hidden;
display: flex;
justify-content: center;
flex-direction: column;
}
.jl>p {
margin: 0 auto;
font-size: 20px;
font-weight: bold;
color: bisque;
}
.jl>span {
font-size: 50px;
line-height: 50px;
text-align: center;
}
</style>
<div class="jl">
<p>节流</p>
<span>1</span>
</div>
<script>
let i = 1;
let flag=true;
let timer = null;
let arr = ['blur', 'red', 'green', 'pink', '#3434e3']
let jl = document.querySelector(".jl");
jl.onclick = function () {
jl.children[1].innerHTML = i++;//children[1]获取的是span元素
if(flag){
flag=false;
timer=setTimeout(()=>{
flag=true
jl.style.backgroundColor = arr[parseInt(Math.random() * 5 + 1)]
},1000)
}
}
</script>
节流效果图


(注:这里颜色只变换了多次,但一秒时间内颜色只变化了一次)
其他的防抖与节流
1.`loadsh防抖与节流`
_.debounce(fn, time) //防抖
_.throttle(fn, time) //节流

浙公网安备 33010602011771号