1. 防抖
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>debounce</title>
</head>
<script>
</script>
<body>
<input type="text" id="input">
<script>
// js 实现防抖
const input = document.getElementById("input")
function debounce(fn,delay){
//timer 是闭包中
let timer = null
return function(){
if(timer){
clearTimeout(timer)
}
timer=setTimeout(()=>{
fn.apply(this,arguments)
timer=null
},delay)
}
}
input.addEventListener("keyup",debounce(()=>{
console.log(input.value)
},500))
</script>
</body>
</html>
2. 节流
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>throttle</title>
</head>
<style>
#root{
width: 200px;
height: 100px;
border: 1px solid red;
}
</style>
<body>
<div id="root" draggable="true">
可拖拽
</div>
<script>
// js 实现节流
const root = document.getElementById("root")
root.addEventListener("drag",throttle(function(e){
console.log(e.offsetX,e.offsetY)
},400))
function throttle(fn,delay){
let timer= null
return function (){
if(timer){
return
}
timer=setTimeout(()=>{
fn.apply(this,arguments)
timer = null
},delay)
}
}
</script>
</body>
</html>