防抖
<!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" id="hInput"></input>
<script>
const inputDOM=document.getElementById('hInput')
function debounce(fn){
let timer=null
return function(){
if(timer){
clearInterval(timer)
}
timer=setTimeout(()=>{
fn()
},1000)
}
}
inputDOM.addEventListener('input',debounce(()=>{console.log('发送请求数据')}))
</script>
</body>
</html>
节流
<!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>
<style>
div {
width: 100px;
height: 100px;
background-color: darkcyan;
}
</style>
</head>
<body>
<div class="box" draggable="true"></div>
<script>
const boxDOM = document.querySelector(".box");
function throttle(fn) {
let timer=null
return function () {
if(timer){
return
}
timer= setTimeout(() => {
fn();
}, 200);
};
}
boxDOM.addEventListener(
"drag",
throttle(() => {
console.log("拖拽");
})
);
</script>
</body>
</html>