js之JavaScript防抖和节流
函数防抖
动作绑定事件,动作发生后一定时间后触发事件,在这段时间内,如果该动作又发生,则重新等待一定时间再触发事件。
应用的场景:一些比较频繁的地方 搜索框
var timer;
document.querySelector('.box').addEventListener('mouseenter', function () {
var th = this;
clearTimeout(timer);
timer = setTimeout(function () {
console.log('鼠标移入进来了')
th.style.backgroundColor = "black";
}, 1000);
})
document.querySelector('.box').addEventListener('mouseout', function () {
var th = this;
clearTimeout(timer);
timer = setTimeout(function () {
console.log('鼠标移出了')
th.style.backgroundColor = "pink";
}, 1000);
})
函数节流
动作绑定事件,动作发生后一段时间后触发事件,在这段时间内,如果动作又发生,则无视该动作,直到事件执行完后,才能重新触发。
var flage = false;
function sum(){
if(flage) return;
flage = true;
setTimeout(function(){
console.log('我被点击了');
flage = false;
},2000)
}