防抖:事件连续触发的,在一段时间内,只执行最后一次
原理:该事件还未执行时再次触发该时间,则这个事件就要重新开始,所以最后表现只执行了最后一次(重新执行)
定时器实现:每次触发下一个定时器之前清除掉之前的定时器
应用场景:文本框输入
<body>
<input type="text" id="input">
<script>
const input = document.querySelector('#input')
input.oninput = debounce(function () {
// 这里的this是window
console.log(this.value)
}, 500)
function debounce(fn, delay) {
var t = null
return function () {
//定时器有值就取消定时器
if (t != null) {
clearTimeout(t)
}
t = setTimeout(() => {
//这里的this是input
fn.call(this)
// console.log(this)
}, delay)
}
}
</script>
</body>
节流:事件连续触发,在一段时间内,只执行一次
原理:多次事件触发过程中,后续触发的事件只能在前边事件结束之后再触发(不打断)
定时器实现:等之前的定时器结束后,才能执行下边的定时器
应用场景:鼠标滑动,快速点击,scroll
鼠标滑动案例:
<!-- 节流是为了控制高频率事件的执行次数 -->
<style>
body {
height: 3000px;
}
</style>
var flag = true
window.onscroll =throttle(function () {
console.log(123)
},500)
function throttle(fn,delay) {
if (flag) {
setTimeout(() => {
fn.call(this)
flag = true
}, delay)
}
flag = false
}
}