防抖和节流都是限制高频事件的触发,防抖是通过一个定时器来延迟事件的执行,当多次触发事件的时候,就重开定时器,重新计时。而节流是将事件限制在一定时间内只能执行一次,多次触发无效。以下为代码,大家可以复制执行以下看看,效果。
<!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{
padding: 10px 30px;
color: white;
background-color: rgb(109, 109, 248);
margin: 10px;
cursor: pointer;
display: inline-block;
}
</style>
</head>
<body>
<div id="debounceBtn">防抖</div>
<div id="throttleBtn">节流</div>
</body>
</html>
<script>
let debounceBtn=document.querySelector('#debounceBtn');
let throttleBtn=document.querySelector('#throttleBtn');
function debounce(fn,wait){
let timer=null;
return function(){
if(timer){
clearTimeout(timer);
timer=null;
}
timer=setTimeout(()=>{
fn.apply(this,arguments)
timer=null;
},wait)
}
}
function throttle(fn,wait){
let pre=Date.now();
return function(){
let now=Date.now();
if(now-pre>wait){
fn.apply(this,arguments);
pre=now;
}
}
}
throttleBtn.addEventListener('click',throttle((e)=>{
console.log(e)
},1000))
debounceBtn.addEventListener('click',debounce((e)=>{
console.log(e)
},1000))
</script>