以监听输入表单和鼠标移动事件为例,使用闭包实现。(也可以通过时间戳实现)
应用场景:提交表单,高频监听事件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input placeholder="请输入">
<div id="box"></div>
<script>
// 提交表单
let getInput = document.querySelector('input')
getInput.addEventListener('input', antiShake(demo, 2000))
function antiShake(fn, wait) {
let timeOut = null
return args => {
if (timeOut) clearTimeout(timeOut)
timeOut = setTimeout(fn, wait)
}
}
function demo() {
console.log('发起请求');
}
// 高频监听事件
let box = document.querySelector('#box')
box.addEventListener("mousemove",throttle(demo,2000))
function throttle(event,time){
let timer = null
return function(){
if(!timer){
timer = setTimeout(()=>{
event()
timer = null
},time)
}
}
}
</script>
</body>
<style>
#box {
background-color: aqua;
width: 200px;
height: 200px;
}
</style>
</html>
节流:一定时间内的多个事件合为一个
防抖:固定时间内,事件只允许发生一次