函数节流是指一定时间内js方法只跑一次。比如人的眨眼睛,就是一定时间内眨一次。这是函数节流最形象的解释。
函数防抖是指频繁触发的情况下,只有足够的空闲时间,才执行代码一次。比如生活中的司机开公交,就是一定时间内,如果有人陆续刷卡上车,司机就不会开车。只有别人没刷卡了,司机才开车。
函数节流
setInterval(()=>{
test()
},200)
// 节流
var canGo=true;
function test() {
if (canGo) {
canGo=false;
setTimeout(() => {
canGo=true;
console.log("节流");
}, 300);
}else{
console.log("未执行");
return;
}
}
函数防抖
let interval=setInterval(()=>{
test()
},200)
setTimeout(() => {
clearInterval(interval)
interval = setInterval(() => {
test()
}, 200)
}, 900);
// 防抖
var time="";
function test() {
clearTimeout(time);
time=setTimeout(() => {
console.log("节流");
}, 300);
console.log("未节流")
}