防抖与节流
防抖
1.防抖:事件触发后n秒后再执行
<style>
div{
width: 100%;
height: 300px;
background-color: #999;
text-align: center;
line-height: 300px;
color: #fff;
font-size: 30px;
}
</style>
<body>
<div>0</div>
</body>
<script>
var div = document.querySelector("div")
var num = 1
function changNum(){
div.innerHTML = num++
}
function bounce(fn,time){
var timer
return function(){
if(timer) clearTimeout(timer)
timer = setTimeout(()=>{
fn.apply(this)
},time)
}
}
div.onmousemove = bounce(changNum,1000)
</script>
2.防抖:事件触发立即执行,n秒后才能再次触发执行
function bounce(fn ,time){
var timer
return function(){
if(timer) clearTimeout(timer)
var callNow = !timer
timer = setTimeout(()=>{
timer = null
},time)
if(callNow) fn.apply(this)
}
}
div.onmousemove = bounce(changNum,1000)
节流
节流:连续发生的事件在n秒内只执行一次函数
1.利用setTimeout实现(消耗性能)
function throttle(fn,time){
var timer
return function(){
if(!timer){
timer = setTimeout(()=>{
timer = null
fn.apply()
},time)
}
}
}
div.onmousemove = throttle(changNum,1000)
2.利用时间戳实行节流
function throttle(fn,time){
var prev = 0
return function(){
var now = new Date()
if(now-prev > time){
fn.apply()
prev = now
}
}
}
div.onmousemove = throttle(changNum,1000)