console
document.getElementById('content')
.addEventListener('mousemove', debounce(handleChangeDebounce))
function handleChangeDebounce(){
console.log(123)
}
function debounce(fn, time = 1000) {
let timeount = null
return function (){
clearTimeout(timeount)
timeount = setTimeout(() => {
fn.apply(this,arguments)
}, time)
}
}
function throttle(fn, time = 1000) {
let isRun = true
return function(){
if(isRun){
isRun = false;
setTimeout(function(){
fn.apply(this,arguments)
isRun = true;
},time)
}
}
}
<div id="content">防抖&&节流</div>
<p>
防抖:触发高频事件后n秒内函数只会执行一次,如果n秒内高频事件再次被触发,则重新计算时间, 最后一次执行。
</p>
<p>节流:高频事件触发,但在n秒内只会执行一次。</p>
#content {
background-color: red;
width: 200px;
height: 200px;
text-align: center;
color: #fff;
}
p {
margin: 0
}