界面基础UI
<body>
<ul id="count">
<li>111</li>
<li>222</li>
<li>333</li>
<li>444</li>
</ul>
<button id="biu">射击🔫</button>
</body>
<style>
*{
margin: 0px;
padding: 0px;
}
#count{
width: 200px;
height: 200px;
border: 1px solid;
overflow-y: auto;
box-sizing: border-box;
}
li{
height: 90px;
}
</style>
防抖:触发事件后在n秒内执行函数,未到n秒再次触发,计时重新计算。
let ulHeight = document.getElementById('count')
function debounce(fn, delay) {
var timer = null;
return function() {
// 清除已存在的定时器
timer && clearTimeout(timer)
timer = setTimeout(function() {
fn.apply(this)
}, delay)
}
}
var fn = function() {
console.log('滚动高度:',ulHeight.scrollTop,'可视高度:',ulHeight.clientHeight,'容器总高度:',ulHeight.scrollHeight);
console.log ('防抖旨在时间段内只触发最后一次执行' + new Date(Date.now()));
}
ulHeight.onscroll = debounce(fn, 1000);
节流:在一定时间内只会执行一次
let biu = document.getElementById('biu')
function throttle(fn, delay) {
// 记录上次触发的时间戳
var lastTime = 0;
return function() {
// 记录当前触发的时间戳
var nowTime = Date.now();
// 如果当前触发与上次触发的时间差值 大于 设置的周期则允许执行
if (nowTime - lastTime > delay) {
fn.call(this);
// 更新时间戳
lastTime = nowTime;
}
}
}
function fn2() {
console.log ('节流旨在时间段内控制触发的频率'+new Date(Date.now()),'biubiubiu')
}
biu.onclick = throttle(fn2, 1000)
应用场景
防抖(debounce)应用场景:
- 每个调整大小/滚动都会触发统计事件。
- 验证文本输入(在连续文本输入后,发送Ajax请求进行验证)。
- 监视滚动scroll事件(在添加去抖动后滚动,只有在用户停止滚动后才会确定它是否已到达页面底部)。
节流(throttle)应用场景:
- 实现DOM元素的拖放功能mousemove。
- 搜索关联keyup。
- 计算鼠标移动距离mousemove。
- 画布模拟草图功能mousemove。
- 射击游戏中的 mousedown/keydown事件(每单位时间只能发射一颗- 子弹)。
- 监视滚动scroll事件(添加节流后,只要滚动页面,就会每隔一段时间才会计算)。