防抖
什么是防抖?
触发事件后n秒内函数只会执行一次,
如果n秒内事件被再次触发,则重新计算时间;
实现步骤?
触发事件(addEventListener)
清楚定时(clearTimeout)
设置定时(setTimeout)
html
<input type="button" value="防抖" id="input"></input>
JavaScript
<script>
const btn = document.querySelector('input');
function handDou() {
console.log('已触发',this); // this指向window
}
// 防抖开始
function antiShake(func,delay) {
let timer;
return function() {
let that = this; // 存贮this指向
let args = arguments; // 增加参数
clearTimeout(timer);
timer = setTimeout(function(){
// func.call(that); // 改变this指向
func.apply(that,args);
},delay)
}
}
btn.addEventListener('click',antiShake(handDou,1000));
</script>