DOM:防抖和节流
防抖和节流
使用场景:
抽奖 登录 动画 网络加载等待需要做防抖或者是节流操作
1、什么是防抖
首先,先去解释一下什么叫做防抖,在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时
2、什么是节流
当持续触发事件时,保证一定时间段内只调用一次事件处理函数。所以节流会稀释函数的执行频率
防抖:
注:setTimeout()方法设置一个定时器,该定时器在定时器到期后执行一个函数或指定的一段代码。
clearTimeout() 方法可取消由 setTimeout() 方法设置的 timeout。
<style> .box { width: 100px; height: 100px; background-color: brown; cursor: pointer; position: absolute; left: 100px; } </style> <div class='box'>hello</div> <script> var box = document.querySelector(".box"); document.onclick = fangdou(function (e) { console.log('hello'); }, 1000) function fangdou(cb, delay) { var timer = null; return function () { clearTimeout(timer); timer = setTimeout(function () { cb() }, delay) } } </script>
防抖优化:
document.onclick = fangdou2(function (e) { console.log(6666, e, this) }, 1000) function fangdou2(cb, delay) { var timer = null; return function () { //return这个函数频率很高 想办法让cb()执行慢下来:防抖 let arg = arguments clearTimeout(timer) timer = setTimeout(() => { cb.apply(this, arg) }, delay) } }
节流:
document.onmousemove = jieliu(function () { console.log(666) }, 20) function jieliu(cb, daley) { var timer = null; return function () { // console.log(66666,timer) if (!timer) { timer = setTimeout(() => { cb(); timer = null }, daley) } } }
节流 优化:
<script>
function jieliu2(cb, daley) {
var timer = null;
return function () {
let arg = arguments
if (!timer) {
timer = setTimeout(() => {
cb.apply(this, arg);
timer = null
}, daley)
}
}
}
let shijianhanshu = jieliu2(function (e) {
box.style.left = e.pageX - box.offsetWidth / 2 + "px"
box.style.top = e.pageY - box.offsetHeight / 2 + "px"
console.log(11111)
}, 17)
document.addEventListener("mousemove", shijianhanshu)
//浏览器的极限绘制频率是60帧 16.7
</script>
浙公网安备 33010602011771号