每日浅浅一决:防抖和节流
1. 防抖
- 概念:当持续触发的事件在一定时间内没有再触发事件时,事件处理函数才会执行一次,如果持续触发的事件在设定的时间到来之前又一次触发了事件,则重新开始延时。
- 使用场景: 表单验证、搜索框输入查询、滚动条滚动、按键提交。
- 代码:
<body style="height: 3600px;">
<input type="text" id="Input">
<script>
var input = document.getElementById("Input")
//处理函数
function handle() {
console.log("松开")
}
// 防抖函数
function debounce(fn, wait) {
let timeout = null
return function() {
// 取消setTimeout()所设定的定时执行操作
clearTimeout(timeout)
/** timeout为调用setTimeout()函数时所获得的返回值,
** 使用该返回标识符作为参数,可以取消该setTimeout()所设定的定时执行操作
**/
timeout = setTimeout(fn, wait)
}
}
input.addEventListener("keyup", debounce(handle, 3000))
window.addEventListener("scroll", debounce(handle, 3000))
</script>
</body>
- 节流
- 概念:当持续触发事件时,保证一定时间段内只调用一次事件处理函数。
- 代码:
<body style="height: 3600px;">
<input type="text" id="Input">
<script>
var input = document.getElementById("Input")
//处理函数
function handle() {
console.log("松开")
}
// 节流函数 时间戳实现
function throttle(fn, delay) {
let lastTime = 0 // 上一次触发的时间
return function() {
let nowTime = Date.now()
if(nowTime - lastTime > delay) {
fn.apply(this)
lastTime = nowTime
}
}
}
// 节流函数 定时器实现
function throttle1(fn, wait) {
let timer = null
return function() {
if(!timer) {
timer = setTimeout(()=>{
fn();
timer = null
}, wait)
}
}
}
// 节流
input.addEventListener("keyup", throttle(handle, 1000))
window.addEventListener1("scroll", throttle(handle, 2000))
</script>
</body>