防抖
比如在百度搜索时,input事件并不会一直触发,会在你停止输入后2s左右触发。这就叫事件防抖
下面是简单小实例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="text" />
</body>
</html>
<script>
function antishake(fn,wait){
let timeOut=null
return function(){
if(timeOut){
clearTimeout(timeOut)
}
timeOut=setTimeout(fn,wait)
}
}
let telInput=document.querySelector('input')
telInput.addEventListener('input',antishake(demo,200))
function demo(){
console.log('发起请求')
}
</script>
节流
使用场景:例如在提交表单时网络卡顿,某些手残党不停的疯狂点击提交按钮,会导致每点击一次就发一次请求,这样就会发无数次请求。那么就要让几秒之内只提交一次。这就是节流
下面是用鼠标滑动举例,在鼠标滑动时,每两秒发一次请求。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
.box{
width: 300px;
height: 300px;
background-color: aqua;
}
</style>
<body>
<div class="box"></div>
</body>
</html>
<script>
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)
}
}
}
function demo(){
console.log('发起请求')
}
</script>